lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | 2b6e5f7ae2a8dcd41b18ec6df01b0e32e90dd660 | 0 | blay09/TwitchIntegration,blay09/TwitchIntegration | package net.blay09.mods.bmc.twitchintegration.handler;
import com.google.common.collect.Maps;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.blay09.mods.bmc.api.BetterMinecraftChatAPI;
import net.blay09.mods.bmc.api.image.IChatRenderable;
import net.blay09.mods.bmc.api.image.ITooltipProvider;
import net.blay09.mods.bmc.balyware.CachedAPI;
import net.blay09.mods.bmc.chat.emotes.twitch.TwitchAPI;
import net.blay09.mods.bmc.twitchintegration.TwitchIntegration;
import net.blay09.mods.bmc.twitchintegration.util.TwitchHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.IResource;
import net.minecraft.util.ResourceLocation;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
public class TwitchBadge {
private static final Map<String, TwitchBadge> twitchBadges = Maps.newHashMap();
private final IChatRenderable chatRenderable;
private final ITooltipProvider tooltipProvider;
public TwitchBadge(IChatRenderable chatRenderable, ITooltipProvider tooltipProvider) {
this.chatRenderable = chatRenderable;
this.tooltipProvider = tooltipProvider;
}
public IChatRenderable getChatRenderable() {
return chatRenderable;
}
public ITooltipProvider getTooltipProvider() {
return tooltipProvider;
}
@Nullable
public static TwitchBadge getSubscriberBadge(String channel) {
TwitchBadge badge = twitchBadges.get(channel);
if(badge == null) {
JsonObject object = CachedAPI.loadCachedAPI("https://api.twitch.tv/kraken/chat/" + channel + "/badges" + "?client_id=" + TwitchHelper.OAUTH_CLIENT_ID, "badges_" + channel);
JsonElement element = object.get("subscriber");
if(!element.isJsonNull()) {
try {
IChatRenderable chatRenderable = BetterMinecraftChatAPI.loadImage(new URI(element.getAsJsonObject().get("image").getAsString()), new File(Minecraft.getMinecraft().mcDataDir, "bmc/cache/badge_" + channel));
chatRenderable.setScale(0.45f);
badge = new TwitchBadge(chatRenderable, ITooltipProvider.EMPTY);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
twitchBadges.put(channel, badge);
}
return badge;
}
public static void loadInbuiltBadge(String name) {
try {
IResource resource = Minecraft.getMinecraft().getResourceManager().getResource(new ResourceLocation(TwitchIntegration.MOD_ID, "badges/badge_" + name + ".png"));
IChatRenderable chatRenderable = BetterMinecraftChatAPI.loadImage(resource.getInputStream(), null);
chatRenderable.setScale(0.45f);
twitchBadges.put(name, new TwitchBadge(chatRenderable, ITooltipProvider.EMPTY));
} catch (IOException e) {
e.printStackTrace();
}
}
@Nullable
public static TwitchBadge getBadge(String name) {
return twitchBadges.get(name);
}
}
| src/main/java/net/blay09/mods/bmc/twitchintegration/handler/TwitchBadge.java | package net.blay09.mods.bmc.twitchintegration.handler;
import com.google.common.collect.Maps;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.blay09.mods.bmc.api.BetterMinecraftChatAPI;
import net.blay09.mods.bmc.api.image.IChatRenderable;
import net.blay09.mods.bmc.api.image.ITooltipProvider;
import net.blay09.mods.bmc.balyware.CachedAPI;
import net.blay09.mods.bmc.twitchintegration.TwitchIntegration;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.IResource;
import net.minecraft.util.ResourceLocation;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
public class TwitchBadge {
private static final Map<String, TwitchBadge> twitchBadges = Maps.newHashMap();
private final IChatRenderable chatRenderable;
private final ITooltipProvider tooltipProvider;
public TwitchBadge(IChatRenderable chatRenderable, ITooltipProvider tooltipProvider) {
this.chatRenderable = chatRenderable;
this.tooltipProvider = tooltipProvider;
}
public IChatRenderable getChatRenderable() {
return chatRenderable;
}
public ITooltipProvider getTooltipProvider() {
return tooltipProvider;
}
@Nullable
public static TwitchBadge getSubscriberBadge(String channel) {
TwitchBadge badge = twitchBadges.get(channel);
if(badge == null) {
JsonObject object = CachedAPI.loadCachedAPI("https://api.twitch.tv/kraken/chat/" + channel + "/badges", "badges_" + channel);
JsonElement element = object.get("subscriber");
if(!element.isJsonNull()) {
try {
IChatRenderable chatRenderable = BetterMinecraftChatAPI.loadImage(new URI(element.getAsJsonObject().get("image").getAsString()), new File(Minecraft.getMinecraft().mcDataDir, "bmc/cache/badge_" + channel));
chatRenderable.setScale(0.45f);
badge = new TwitchBadge(chatRenderable, ITooltipProvider.EMPTY);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
twitchBadges.put(channel, badge);
}
return badge;
}
public static void loadInbuiltBadge(String name) {
try {
IResource resource = Minecraft.getMinecraft().getResourceManager().getResource(new ResourceLocation(TwitchIntegration.MOD_ID, "badges/badge_" + name + ".png"));
IChatRenderable chatRenderable = BetterMinecraftChatAPI.loadImage(resource.getInputStream(), null);
chatRenderable.setScale(0.45f);
twitchBadges.put(name, new TwitchBadge(chatRenderable, ITooltipProvider.EMPTY));
} catch (IOException e) {
e.printStackTrace();
}
}
@Nullable
public static TwitchBadge getBadge(String name) {
return twitchBadges.get(name);
}
}
| Add client_id to badge API call.
| src/main/java/net/blay09/mods/bmc/twitchintegration/handler/TwitchBadge.java | Add client_id to badge API call. | <ide><path>rc/main/java/net/blay09/mods/bmc/twitchintegration/handler/TwitchBadge.java
<ide> import net.blay09.mods.bmc.api.image.IChatRenderable;
<ide> import net.blay09.mods.bmc.api.image.ITooltipProvider;
<ide> import net.blay09.mods.bmc.balyware.CachedAPI;
<add>import net.blay09.mods.bmc.chat.emotes.twitch.TwitchAPI;
<ide> import net.blay09.mods.bmc.twitchintegration.TwitchIntegration;
<add>import net.blay09.mods.bmc.twitchintegration.util.TwitchHelper;
<ide> import net.minecraft.client.Minecraft;
<ide> import net.minecraft.client.resources.IResource;
<ide> import net.minecraft.util.ResourceLocation;
<ide> public static TwitchBadge getSubscriberBadge(String channel) {
<ide> TwitchBadge badge = twitchBadges.get(channel);
<ide> if(badge == null) {
<del> JsonObject object = CachedAPI.loadCachedAPI("https://api.twitch.tv/kraken/chat/" + channel + "/badges", "badges_" + channel);
<add> JsonObject object = CachedAPI.loadCachedAPI("https://api.twitch.tv/kraken/chat/" + channel + "/badges" + "?client_id=" + TwitchHelper.OAUTH_CLIENT_ID, "badges_" + channel);
<ide> JsonElement element = object.get("subscriber");
<ide> if(!element.isJsonNull()) {
<ide> try { |
|
Java | apache-2.0 | b4299b4a80a715ae111c9791c33e144eb7e3e1f7 | 0 | SpineEventEngine/todo-list,SpineEventEngine/todo-list,SpineEventEngine/todo-list,SpineEventEngine/todo-list,SpineEventEngine/todo-list,SpineEventEngine/todo-list | /*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.examples.todolist.c.aggregates;
import com.google.protobuf.Message;
import org.spine3.examples.todolist.TaskCreation;
import org.spine3.examples.todolist.TaskDetails;
import org.spine3.examples.todolist.TaskId;
import org.spine3.examples.todolist.TaskStatus;
import org.spine3.examples.todolist.c.commands.CreateBasicTask;
import org.spine3.examples.todolist.c.commands.CreateDraft;
import org.spine3.examples.todolist.c.events.TaskCreated;
import org.spine3.examples.todolist.c.events.TaskDraftCreated;
import org.spine3.examples.todolist.c.failures.CannotCreateBasicTask;
import org.spine3.examples.todolist.c.failures.CannotCreateDraft;
import org.spine3.examples.todolist.c.failures.CannotCreateTaskWithInappropriateDescription;
import org.spine3.protobuf.Timestamps;
import org.spine3.server.aggregate.AggregatePart;
import org.spine3.server.aggregate.Apply;
import org.spine3.server.command.Assign;
import java.util.Collections;
import java.util.List;
import static org.spine3.examples.todolist.c.aggregates.FailureHelper.throwCannotCreateDraftFailure;
import static org.spine3.examples.todolist.c.aggregates.FailureHelper.throwCannotCreateTaskWithInappropriateDescription;
/**
* @author Illia Shepilov
*/
public class TaskCreationPart extends AggregatePart<TaskId, TaskCreation, TaskCreation.Builder> {
private static final int MIN_DESCRIPTION_LENGTH = 3;
/**
* {@inheritDoc}
*
* @param id
*/
protected TaskCreationPart(TaskId id) {
super(id);
}
@Assign
List<? extends Message> handle(CreateBasicTask cmd)
throws CannotCreateBasicTask, CannotCreateTaskWithInappropriateDescription {
validateCommand(cmd);
final TaskId taskId = cmd.getId();
final TaskDetails.Builder taskDetails = TaskDetails.newBuilder()
.setDescription(cmd.getDescription());
final TaskCreated result = TaskCreated.newBuilder()
.setId(taskId)
.setDetails(taskDetails)
.build();
return Collections.singletonList(result);
}
@Assign
List<? extends Message> handle(CreateDraft cmd) throws CannotCreateDraft {
final TaskId taskId = cmd.getId();
final boolean isValid = TaskFlowValidator.isValidCreateDraftCommand(getState().getTaskStatus());
if (!isValid) {
throwCannotCreateDraftFailure(taskId);
}
final TaskDraftCreated draftCreated = TaskDraftCreated.newBuilder()
.setId(taskId)
.setDraftCreationTime(Timestamps.getCurrentTime())
.build();
final List<TaskDraftCreated> result = Collections.singletonList(draftCreated);
return result;
}
@Apply
private void taskCreated(TaskCreated event) {
final TaskDetails taskDetails = event.getDetails();
getBuilder().setTaskId(event.getId())
.setDescription(taskDetails.getDescription())
.setTaskStatus(TaskStatus.FINALIZED);
}
@Apply
private void draftCreated(TaskDraftCreated event) {
getBuilder().setTaskId(event.getId())
.setDescription(event.getDetails()
.getDescription())
.setTaskStatus(TaskStatus.DRAFT);
}
private static void validateCommand(CreateBasicTask cmd)
throws CannotCreateBasicTask, CannotCreateTaskWithInappropriateDescription {
final String description = cmd.getDescription();
if (description != null && description.length() < MIN_DESCRIPTION_LENGTH) {
final TaskId taskId = cmd.getId();
throwCannotCreateTaskWithInappropriateDescription(taskId);
}
}
}
| api-java/src/main/java/org/spine3/examples/todolist/c/aggregates/TaskCreationPart.java | /*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.examples.todolist.c.aggregates;
import com.google.protobuf.Message;
import org.spine3.examples.todolist.TaskCreation;
import org.spine3.examples.todolist.TaskDetails;
import org.spine3.examples.todolist.TaskId;
import org.spine3.examples.todolist.TaskStatus;
import org.spine3.examples.todolist.c.commands.CreateBasicTask;
import org.spine3.examples.todolist.c.commands.CreateDraft;
import org.spine3.examples.todolist.c.commands.FinalizeDraft;
import org.spine3.examples.todolist.c.events.TaskCreated;
import org.spine3.examples.todolist.c.events.TaskDraftCreated;
import org.spine3.examples.todolist.c.events.TaskDraftFinalized;
import org.spine3.examples.todolist.c.failures.CannotCreateBasicTask;
import org.spine3.examples.todolist.c.failures.CannotCreateDraft;
import org.spine3.examples.todolist.c.failures.CannotCreateTaskWithInappropriateDescription;
import org.spine3.examples.todolist.c.failures.CannotFinalizeDraft;
import org.spine3.protobuf.Timestamps;
import org.spine3.server.aggregate.AggregatePart;
import org.spine3.server.aggregate.Apply;
import org.spine3.server.command.Assign;
import java.util.Collections;
import java.util.List;
import static org.spine3.examples.todolist.c.aggregates.AggregateHelper.generateExceptionMessage;
import static org.spine3.examples.todolist.c.aggregates.FailureHelper.throwCannotCreateDraftFailure;
import static org.spine3.examples.todolist.c.aggregates.FailureHelper.throwCannotCreateTaskWithInappropriateDescription;
import static org.spine3.examples.todolist.c.aggregates.FailureHelper.throwCannotFinalizeDraftFailure;
/**
* @author Illia Shepilov
*/
public class TaskCreationPart extends AggregatePart<TaskId, TaskCreation, TaskCreation.Builder> {
private static final int MIN_DESCRIPTION_LENGTH = 3;
/**
* {@inheritDoc}
*
* @param id
*/
protected TaskCreationPart(TaskId id) {
super(id);
}
@Assign
List<? extends Message> handle(CreateBasicTask cmd)
throws CannotCreateBasicTask, CannotCreateTaskWithInappropriateDescription {
validateCommand(cmd);
final TaskId taskId = cmd.getId();
final TaskDetails.Builder taskDetails = TaskDetails.newBuilder()
.setDescription(cmd.getDescription());
final TaskCreated result = TaskCreated.newBuilder()
.setId(taskId)
.setDetails(taskDetails)
.build();
return Collections.singletonList(result);
}
@Assign
List<? extends Message> handle(CreateDraft cmd) throws CannotCreateDraft {
final TaskId taskId = cmd.getId();
final boolean isValid = TaskFlowValidator.isValidCreateDraftCommand(getState().getTaskStatus());
if (!isValid) {
throwCannotCreateDraftFailure(taskId);
}
final TaskDraftCreated draftCreated = TaskDraftCreated.newBuilder()
.setId(taskId)
.setDraftCreationTime(Timestamps.getCurrentTime())
.build();
final List<TaskDraftCreated> result = Collections.singletonList(draftCreated);
return result;
}
@Apply
private void taskCreated(TaskCreated event) {
final TaskDetails taskDetails = event.getDetails();
getBuilder().setTaskId(event.getId())
.setDescription(taskDetails.getDescription())
.setTaskStatus(TaskStatus.FINALIZED);
}
@Apply
private void draftCreated(TaskDraftCreated event) {
getBuilder().setTaskId(event.getId())
.setDescription(event.getDetails()
.getDescription())
.setTaskStatus(TaskStatus.DRAFT);
}
private static void validateCommand(CreateBasicTask cmd)
throws CannotCreateBasicTask, CannotCreateTaskWithInappropriateDescription {
final String description = cmd.getDescription();
if (description != null && description.length() < MIN_DESCRIPTION_LENGTH) {
final TaskId taskId = cmd.getId();
throwCannotCreateTaskWithInappropriateDescription(taskId);
}
}
}
| Remove unused imports.
| api-java/src/main/java/org/spine3/examples/todolist/c/aggregates/TaskCreationPart.java | Remove unused imports. | <ide><path>pi-java/src/main/java/org/spine3/examples/todolist/c/aggregates/TaskCreationPart.java
<ide> import org.spine3.examples.todolist.TaskStatus;
<ide> import org.spine3.examples.todolist.c.commands.CreateBasicTask;
<ide> import org.spine3.examples.todolist.c.commands.CreateDraft;
<del>import org.spine3.examples.todolist.c.commands.FinalizeDraft;
<ide> import org.spine3.examples.todolist.c.events.TaskCreated;
<ide> import org.spine3.examples.todolist.c.events.TaskDraftCreated;
<del>import org.spine3.examples.todolist.c.events.TaskDraftFinalized;
<ide> import org.spine3.examples.todolist.c.failures.CannotCreateBasicTask;
<ide> import org.spine3.examples.todolist.c.failures.CannotCreateDraft;
<ide> import org.spine3.examples.todolist.c.failures.CannotCreateTaskWithInappropriateDescription;
<del>import org.spine3.examples.todolist.c.failures.CannotFinalizeDraft;
<ide> import org.spine3.protobuf.Timestamps;
<ide> import org.spine3.server.aggregate.AggregatePart;
<ide> import org.spine3.server.aggregate.Apply;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide>
<del>import static org.spine3.examples.todolist.c.aggregates.AggregateHelper.generateExceptionMessage;
<ide> import static org.spine3.examples.todolist.c.aggregates.FailureHelper.throwCannotCreateDraftFailure;
<ide> import static org.spine3.examples.todolist.c.aggregates.FailureHelper.throwCannotCreateTaskWithInappropriateDescription;
<del>import static org.spine3.examples.todolist.c.aggregates.FailureHelper.throwCannotFinalizeDraftFailure;
<ide>
<ide> /**
<ide> * @author Illia Shepilov |
|
Java | apache-2.0 | ca1cc84aab548ac840dcdeda4035d990c569ca84 | 0 | selckin/wicket,bitstorm/wicket,klopfdreh/wicket,aldaris/wicket,klopfdreh/wicket,apache/wicket,topicusonderwijs/wicket,apache/wicket,AlienQueen/wicket,apache/wicket,freiheit-com/wicket,AlienQueen/wicket,aldaris/wicket,topicusonderwijs/wicket,mosoft521/wicket,topicusonderwijs/wicket,dashorst/wicket,dashorst/wicket,selckin/wicket,freiheit-com/wicket,selckin/wicket,astrapi69/wicket,dashorst/wicket,bitstorm/wicket,AlienQueen/wicket,klopfdreh/wicket,aldaris/wicket,mosoft521/wicket,freiheit-com/wicket,topicusonderwijs/wicket,dashorst/wicket,bitstorm/wicket,klopfdreh/wicket,AlienQueen/wicket,topicusonderwijs/wicket,astrapi69/wicket,klopfdreh/wicket,selckin/wicket,apache/wicket,bitstorm/wicket,selckin/wicket,freiheit-com/wicket,mosoft521/wicket,mosoft521/wicket,dashorst/wicket,AlienQueen/wicket,aldaris/wicket,freiheit-com/wicket,bitstorm/wicket,apache/wicket,aldaris/wicket,mosoft521/wicket,astrapi69/wicket,astrapi69/wicket | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.request.resource.caching.version;
import org.apache.wicket.request.resource.caching.IStaticCacheableResource;
import org.apache.wicket.util.resource.IResourceStream;
import org.apache.wicket.util.time.Time;
/**
* Uses the last modified timestamp of a {@link org.apache.wicket.request.resource.caching.IStaticCacheableResource}
* converted to milliseconds as a version string.
*
* @author Peter Ertl
*
* @since 1.5
*/
public class LastModifiedResourceVersion implements IResourceVersion
{
@Override
public String getVersion(IStaticCacheableResource resource)
{
// get last modified timestamp of resource
IResourceStream stream = resource.getCacheableResourceStream();
// if resource stream can not be found do not cache
if (stream == null)
{
return null;
}
final Time lastModified = stream.lastModifiedTime();
// if no timestamp is available we can not provide a version
if (lastModified == null)
{
return null;
}
// version string = last modified timestamp converted to milliseconds
return String.valueOf(lastModified.getMilliseconds());
}
}
| wicket-core/src/main/java/org/apache/wicket/request/resource/caching/version/LastModifiedResourceVersion.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.request.resource.caching.version;
import org.apache.wicket.request.resource.caching.IStaticCacheableResource;
import org.apache.wicket.util.resource.IResourceStream;
import org.apache.wicket.util.time.Time;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Uses the last modified timestamp of a {@link org.apache.wicket.request.resource.caching.IStaticCacheableResource}
* converted to milliseconds as a version string.
*
* @author Peter Ertl
*
* @since 1.5
*/
public class LastModifiedResourceVersion implements IResourceVersion
{
private static final Logger log = LoggerFactory.getLogger(LastModifiedResourceVersion.class);
@Override
public String getVersion(IStaticCacheableResource resource)
{
// get last modified timestamp of resource
IResourceStream stream = resource.getCacheableResourceStream();
// if resource stream can not be found do not cache
if (stream == null)
{
return null;
}
final Time lastModified = stream.lastModifiedTime();
// if no timestamp is available we can not provide a version
if (lastModified == null)
{
return null;
}
// version string = last modified timestamp converted to milliseconds
return String.valueOf(lastModified.getMilliseconds());
}
}
| Remove unused logger
| wicket-core/src/main/java/org/apache/wicket/request/resource/caching/version/LastModifiedResourceVersion.java | Remove unused logger | <ide><path>icket-core/src/main/java/org/apache/wicket/request/resource/caching/version/LastModifiedResourceVersion.java
<ide> import org.apache.wicket.request.resource.caching.IStaticCacheableResource;
<ide> import org.apache.wicket.util.resource.IResourceStream;
<ide> import org.apache.wicket.util.time.Time;
<del>import org.slf4j.Logger;
<del>import org.slf4j.LoggerFactory;
<ide>
<ide> /**
<ide> * Uses the last modified timestamp of a {@link org.apache.wicket.request.resource.caching.IStaticCacheableResource}
<ide> */
<ide> public class LastModifiedResourceVersion implements IResourceVersion
<ide> {
<del> private static final Logger log = LoggerFactory.getLogger(LastModifiedResourceVersion.class);
<del>
<ide> @Override
<ide> public String getVersion(IStaticCacheableResource resource)
<ide> { |
|
Java | lgpl-2.1 | 46c087353b4109bc1716a5b15e04bf5c3981a034 | 0 | Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,JoeCarlson/intermine,elsiklab/intermine,tomck/intermine,zebrafishmine/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,zebrafishmine/intermine,JoeCarlson/intermine,elsiklab/intermine,joshkh/intermine,kimrutherford/intermine,drhee/toxoMine,tomck/intermine,justincc/intermine,elsiklab/intermine,tomck/intermine,elsiklab/intermine,JoeCarlson/intermine,elsiklab/intermine,drhee/toxoMine,joshkh/intermine,kimrutherford/intermine,zebrafishmine/intermine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,joshkh/intermine,zebrafishmine/intermine,joshkh/intermine,JoeCarlson/intermine,drhee/toxoMine,JoeCarlson/intermine,tomck/intermine,JoeCarlson/intermine,justincc/intermine,kimrutherford/intermine,zebrafishmine/intermine,elsiklab/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,zebrafishmine/intermine,drhee/toxoMine,zebrafishmine/intermine,drhee/toxoMine,justincc/intermine,joshkh/intermine,kimrutherford/intermine,justincc/intermine,justincc/intermine,JoeCarlson/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,kimrutherford/intermine,justincc/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,tomck/intermine,joshkh/intermine,justincc/intermine,kimrutherford/intermine,justincc/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,tomck/intermine,kimrutherford/intermine,tomck/intermine,zebrafishmine/intermine | package org.intermine.web.struts;
/*
* Copyright (C) 2002-2010 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.io.PrintStream;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.TagManager;
import org.intermine.api.search.SearchRepository;
import org.intermine.api.tag.TagTypes;
import org.intermine.api.template.TemplateQuery;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.XmlUtil;
import org.intermine.web.logic.session.SessionMethods;
/**
* Action that results from a button press on the user profile page.
*
* @author Mark Woodbridge
* @author Thomas Riley
*/
public class ModifyTemplateAction extends InterMineAction
{
/**
* Forward to the correct method based on the button pressed.
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws
* an exception
*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModifyTemplateForm mtf = (ModifyTemplateForm) form;
ActionErrors errors = mtf.validate(mapping, request);
if (errors == null || errors.isEmpty()) {
if (request.getParameter("delete") != null) {
errors = delete(mapping, form, request, response);
} else if (request.getParameter("export") != null || mtf.getTemplateButton() != null) {
export(mapping, form, request, response);
}
}
saveErrors(request, (ActionMessages) errors);
return getReturn(mtf.getPageName(), mapping);
}
/**
* Delete some templates.
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return errors The errors, if any, encountered whilst attempting to delete templates
* @exception Exception if the application business logic throws
* an exception
*/
public ActionErrors delete(@SuppressWarnings("unused") ActionMapping mapping,
ActionForm form, HttpServletRequest request,
@SuppressWarnings("unused") HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
InterMineAPI im = SessionMethods.getInterMineAPI(session);
ServletContext servletContext = session.getServletContext();
Profile profile = SessionMethods.getProfile(session);
ModifyTemplateForm mqf = (ModifyTemplateForm) form;
ActionErrors errors = new ActionErrors();
try {
profile.disableSaving();
for (int i = 0; i < mqf.getSelected().length; i++) {
String template = mqf.getSelected()[i];
// if this template is not one of theirs
if (profile.getTemplate(template) == null) {
errors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("errors.modifyTemplate.delete"));
}
profile.deleteTemplate(template);
}
if (SessionMethods.isSuperUser(session)) {
SearchRepository tr = SessionMethods.getGlobalSearchRepository(servletContext);
tr.globalChange(TagTypes.TEMPLATE);
}
} finally {
profile.enableSaving();
}
return errors;
}
/**
* Export the selected templates.
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @exception Exception if the application business logic throws
* an exception
*/
public void export(@SuppressWarnings("unused") ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
ModifyTemplateForm mqf = (ModifyTemplateForm) form;
ServletContext servletContext = session.getServletContext();
response.setContentType("text/plain");
response.setHeader("Content-Disposition ", "inline; filename=template-queries.xml");
PrintStream out = new PrintStream(response.getOutputStream());
out.println("<template-queries>");
Map myTemplates = profile.getSavedTemplates();
Map publicTemplates = im.getProfileManager().getSuperuserProfile().getSavedTemplates();
for (int i = 0; i < mqf.getSelected().length; i++) {
String name = mqf.getSelected()[i];
String xml = null;
if (publicTemplates.get(name) != null) {
xml = ((TemplateQuery) publicTemplates.get(name)).toXml(PathQuery
.USERPROFILE_VERSION);
} else if (myTemplates.get(name) != null) {
xml = ((TemplateQuery) myTemplates.get(name)).toXml(PathQuery.USERPROFILE_VERSION);
}
if (xml != null) {
xml = XmlUtil.indentXmlSimple(xml);
out.println(xml);
}
}
out.println("</template-queries>");
out.flush();
}
private ActionForward getReturn(String pageName, ActionMapping mapping) {
if (pageName != null && "MyMine".equals(pageName)) {
return mapping.findForward("mymine");
}
return mapping.findForward("templates");
}
}
| intermine/web/main/src/org/intermine/web/struts/ModifyTemplateAction.java | package org.intermine.web.struts;
/*
* Copyright (C) 2002-2010 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.io.PrintStream;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.TagManager;
import org.intermine.api.search.SearchRepository;
import org.intermine.api.tag.TagTypes;
import org.intermine.api.template.TemplateQuery;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.XmlUtil;
import org.intermine.web.logic.session.SessionMethods;
/**
* Action that results from a button press on the user profile page.
*
* @author Mark Woodbridge
* @author Thomas Riley
*/
public class ModifyTemplateAction extends InterMineAction
{
/**
* Forward to the correct method based on the button pressed.
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws
* an exception
*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModifyTemplateForm mtf = (ModifyTemplateForm) form;
ActionErrors errors = mtf.validate(mapping, request);
if (errors == null || errors.isEmpty()) {
if (request.getParameter("delete") != null) {
errors = delete(mapping, form, request, response);
} else if (request.getParameter("export") != null || mtf.getTemplateButton() != null) {
export(mapping, form, request, response);
}
}
saveErrors(request, (ActionMessages) errors);
return getReturn(mtf.getPageName(), mapping);
}
/**
* Delete some templates.
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return errors The errors, if any, encountered whilst attempting to delete templates
* @exception Exception if the application business logic throws
* an exception
*/
public ActionErrors delete(@SuppressWarnings("unused") ActionMapping mapping,
ActionForm form, HttpServletRequest request,
@SuppressWarnings("unused") HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
InterMineAPI im = SessionMethods.getInterMineAPI(session);
ServletContext servletContext = session.getServletContext();
Profile profile = SessionMethods.getProfile(session);
ModifyTemplateForm mqf = (ModifyTemplateForm) form;
ActionErrors errors = new ActionErrors();
try {
profile.disableSaving();
for (int i = 0; i < mqf.getSelected().length; i++) {
String template = mqf.getSelected()[i];
// if this template is not one of theirs
if (profile.getTemplate(template) == null) {
errors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("errors.modifyTemplate.delete"));
}
profile.deleteTemplate(template);
TagManager tagManager = im.getTagManager();
//delete its tags
Set<String> tagNames = tagManager.getObjectTagNames(template, TagTypes.TEMPLATE,
profile.getUsername());
for (String tagName : tagNames) {
tagManager.deleteTag(tagName, template, TagTypes.TEMPLATE,
profile.getUsername());
}
}
if (SessionMethods.isSuperUser(session)) {
SearchRepository tr = SessionMethods.getGlobalSearchRepository(servletContext);
tr.globalChange(TagTypes.TEMPLATE);
}
} finally {
profile.enableSaving();
}
return errors;
}
/**
* Export the selected templates.
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @exception Exception if the application business logic throws
* an exception
*/
public void export(@SuppressWarnings("unused") ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
ModifyTemplateForm mqf = (ModifyTemplateForm) form;
ServletContext servletContext = session.getServletContext();
response.setContentType("text/plain");
response.setHeader("Content-Disposition ", "inline; filename=template-queries.xml");
PrintStream out = new PrintStream(response.getOutputStream());
out.println("<template-queries>");
Map myTemplates = profile.getSavedTemplates();
Map publicTemplates = im.getProfileManager().getSuperuserProfile().getSavedTemplates();
for (int i = 0; i < mqf.getSelected().length; i++) {
String name = mqf.getSelected()[i];
String xml = null;
if (publicTemplates.get(name) != null) {
xml = ((TemplateQuery) publicTemplates.get(name)).toXml(PathQuery
.USERPROFILE_VERSION);
} else if (myTemplates.get(name) != null) {
xml = ((TemplateQuery) myTemplates.get(name)).toXml(PathQuery.USERPROFILE_VERSION);
}
if (xml != null) {
xml = XmlUtil.indentXmlSimple(xml);
out.println(xml);
}
}
out.println("</template-queries>");
out.flush();
}
private ActionForward getReturn(String pageName, ActionMapping mapping) {
if (pageName != null && "MyMine".equals(pageName)) {
return mapping.findForward("mymine");
}
return mapping.findForward("templates");
}
}
| The tags are deleted by the deleteTemplate method
| intermine/web/main/src/org/intermine/web/struts/ModifyTemplateAction.java | The tags are deleted by the deleteTemplate method | <ide><path>ntermine/web/main/src/org/intermine/web/struts/ModifyTemplateAction.java
<ide> }
<ide>
<ide> profile.deleteTemplate(template);
<del> TagManager tagManager = im.getTagManager();
<del> //delete its tags
<del> Set<String> tagNames = tagManager.getObjectTagNames(template, TagTypes.TEMPLATE,
<del> profile.getUsername());
<del> for (String tagName : tagNames) {
<del> tagManager.deleteTag(tagName, template, TagTypes.TEMPLATE,
<del> profile.getUsername());
<del> }
<ide> }
<ide>
<ide> if (SessionMethods.isSuperUser(session)) { |
|
Java | lgpl-2.1 | d50ec083eb525d45ddeef627b998224f604e9409 | 0 | aaronc/jfreechart,aaronc/jfreechart,aaronc/jfreechart | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* -----------------
* DateTickUnit.java
* -----------------
* (C) Copyright 2000-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Chris Boek;
*
* Changes
* -------
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 27-Nov-2002 : Added IllegalArgumentException to getMillisecondCount()
* method (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 12-Nov-2003 : Added roll fields that can improve the labelling on segmented
* date axes (DG);
* 03-Dec-2003 : DateFormat constructor argument is now filled with an default
* if null (TM);
* 07-Dec-2003 : Fixed bug (null pointer exception) in constructor (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 21-Mar-2007 : Added toString() for debugging (DG);
* 04-Apr-2007 : Added new methods addToDate(Date, TimeZone) and rollDate(Date,
* TimeZone) (CB);
* 09-Jun-2008 : Deprecated addToDate(Date) (DG);
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.jfree.util.ObjectUtilities;
/**
* A tick unit for use by subclasses of {@link DateAxis}. Instances of this
* class are immutable.
*/
public class DateTickUnit extends TickUnit implements Serializable {
/** For serialization. */
private static final long serialVersionUID = -7289292157229621901L;
/** A constant for years. */
public static final int YEAR = 0;
/** A constant for months. */
public static final int MONTH = 1;
/** A constant for days. */
public static final int DAY = 2;
/** A constant for hours. */
public static final int HOUR = 3;
/** A constant for minutes. */
public static final int MINUTE = 4;
/** A constant for seconds. */
public static final int SECOND = 5;
/** A constant for milliseconds. */
public static final int MILLISECOND = 6;
/** The unit. */
private int unit;
/** The unit count. */
private int count;
/** The roll unit. */
private int rollUnit;
/** The roll count. */
private int rollCount;
/** The date formatter. */
private DateFormat formatter;
/**
* Creates a new date tick unit. The dates will be formatted using a
* SHORT format for the default locale.
*
* @param unit the unit.
* @param count the unit count.
*/
public DateTickUnit(int unit, int count) {
this(unit, count, null);
}
/**
* Creates a new date tick unit. You can specify the units using one of
* the constants YEAR, MONTH, DAY, HOUR, MINUTE, SECOND or MILLISECOND.
* In addition, you can specify a unit count, and a date format.
*
* @param unit the unit.
* @param count the unit count.
* @param formatter the date formatter (defaults to DateFormat.SHORT).
*/
public DateTickUnit(int unit, int count, DateFormat formatter) {
this(unit, count, unit, count, formatter);
}
/**
* Creates a new unit.
*
* @param unit the unit.
* @param count the count.
* @param rollUnit the roll unit.
* @param rollCount the roll count.
* @param formatter the date formatter (defaults to DateFormat.SHORT).
*/
public DateTickUnit(int unit, int count, int rollUnit, int rollCount,
DateFormat formatter) {
super(DateTickUnit.getMillisecondCount(unit, count));
this.unit = unit;
this.count = count;
this.rollUnit = rollUnit;
this.rollCount = rollCount;
this.formatter = formatter;
if (formatter == null) {
this.formatter = DateFormat.getDateInstance(DateFormat.SHORT);
}
}
/**
* Returns the date unit. This will be one of the constants
* <code>YEAR</code>, <code>MONTH</code>, <code>DAY</code>,
* <code>HOUR</code>, <code>MINUTE</code>, <code>SECOND</code> or
* <code>MILLISECOND</code>, defined by this class. Note that these
* constants do NOT correspond to those defined in Java's
* <code>Calendar</code> class.
*
* @return The date unit.
*/
public int getUnit() {
return this.unit;
}
/**
* Returns the unit count.
*
* @return The unit count.
*/
public int getCount() {
return this.count;
}
/**
* Returns the roll unit. This is the amount by which the tick advances if
* it is "hidden" when displayed on a segmented date axis. Typically the
* roll will be smaller than the regular tick unit (for example, a 7 day
* tick unit might use a 1 day roll).
*
* @return The roll unit.
*/
public int getRollUnit() {
return this.rollUnit;
}
/**
* Returns the roll count.
*
* @return The roll count.
*/
public int getRollCount() {
return this.rollCount;
}
/**
* Formats a value.
*
* @param milliseconds date in milliseconds since 01-01-1970.
*
* @return The formatted date.
*/
public String valueToString(double milliseconds) {
return this.formatter.format(new Date((long) milliseconds));
}
/**
* Formats a date using the tick unit's formatter.
*
* @param date the date.
*
* @return The formatted date.
*/
public String dateToString(Date date) {
return this.formatter.format(date);
}
/**
* Calculates a new date by adding this unit to the base date, with
* calculations performed in the default timezone and locale.
*
* @param base the base date.
*
* @return A new date one unit after the base date.
*
* @see #addToDate(Date, TimeZone)
*
* @deprecated As of JFreeChart 1.0.10, this method is deprecated - you
* should use {@link #addToDate(Date, TimeZone)} instead.
*/
public Date addToDate(Date base) {
return addToDate(base, TimeZone.getDefault());
}
/**
* Calculates a new date by adding this unit to the base date.
*
* @param base the base date.
* @param zone the time zone for the date calculation.
*
* @return A new date one unit after the base date.
*
* @since 1.0.6
*/
public Date addToDate(Date base, TimeZone zone) {
// as far as I know, the Locale for the calendar only affects week
// number calculations, and since DateTickUnit doesn't do week
// arithmetic, the default locale (whatever it is) should be fine
// here...
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(base);
calendar.add(getCalendarField(this.unit), this.count);
return calendar.getTime();
}
/**
* Rolls the date forward by the amount specified by the roll unit and
* count.
*
* @param base the base date.
* @return The rolled date.
*
* @see #rollDate(Date, TimeZone)
*/
public Date rollDate(Date base) {
return rollDate(base, TimeZone.getDefault());
}
/**
* Rolls the date forward by the amount specified by the roll unit and
* count.
*
* @param base the base date.
* @param zone the time zone.
*
* @return The rolled date.
*
* @since 1.0.6
*/
public Date rollDate(Date base, TimeZone zone) {
// as far as I know, the Locale for the calendar only affects week
// number calculations, and since DateTickUnit doesn't do week
// arithmetic, the default locale (whatever it is) should be fine
// here...
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(base);
calendar.add(getCalendarField(this.rollUnit), this.rollCount);
return calendar.getTime();
}
/**
* Returns a field code that can be used with the <code>Calendar</code>
* class.
*
* @return The field code.
*/
public int getCalendarField() {
return getCalendarField(this.unit);
}
/**
* Returns a field code (that can be used with the Calendar class) for a
* given 'unit' code. The 'unit' is one of: {@link #YEAR}, {@link #MONTH},
* {@link #DAY}, {@link #HOUR}, {@link #MINUTE}, {@link #SECOND} and
* {@link #MILLISECOND}.
*
* @param tickUnit the unit.
*
* @return The field code.
*/
private int getCalendarField(int tickUnit) {
switch (tickUnit) {
case (YEAR):
return Calendar.YEAR;
case (MONTH):
return Calendar.MONTH;
case (DAY):
return Calendar.DATE;
case (HOUR):
return Calendar.HOUR_OF_DAY;
case (MINUTE):
return Calendar.MINUTE;
case (SECOND):
return Calendar.SECOND;
case (MILLISECOND):
return Calendar.MILLISECOND;
default:
return Calendar.MILLISECOND;
}
}
/**
* Returns the (approximate) number of milliseconds for the given unit and
* unit count.
* <P>
* This value is an approximation some of the time (e.g. months are
* assumed to have 31 days) but this shouldn't matter.
*
* @param unit the unit.
* @param count the unit count.
*
* @return The number of milliseconds.
*/
private static long getMillisecondCount(int unit, int count) {
switch (unit) {
case (YEAR):
return (365L * 24L * 60L * 60L * 1000L) * count;
case (MONTH):
return (31L * 24L * 60L * 60L * 1000L) * count;
case (DAY):
return (24L * 60L * 60L * 1000L) * count;
case (HOUR):
return (60L * 60L * 1000L) * count;
case (MINUTE):
return (60L * 1000L) * count;
case (SECOND):
return 1000L * count;
case (MILLISECOND):
return count;
default:
throw new IllegalArgumentException(
"DateTickUnit.getMillisecondCount() : unit must "
+ "be one of the constants YEAR, MONTH, DAY, HOUR, MINUTE, "
+ "SECOND or MILLISECOND defined in the DateTickUnit "
+ "class. Do *not* use the constants defined in "
+ "java.util.Calendar."
);
}
}
/**
* Tests this unit for equality with another object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return <code>true</code> or <code>false</code>.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof DateTickUnit)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
DateTickUnit that = (DateTickUnit) obj;
if (this.unit != that.unit) {
return false;
}
if (this.count != that.count) {
return false;
}
if (!ObjectUtilities.equal(this.formatter, that.formatter)) {
return false;
}
return true;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
public int hashCode() {
int result = 19;
result = 37 * result + this.unit;
result = 37 * result + this.count;
result = 37 * result + this.formatter.hashCode();
return result;
}
/**
* Strings for use by the toString() method.
*/
private static final String[] units = {"YEAR", "MONTH", "DAY", "HOUR",
"MINUTE", "SECOND", "MILLISECOND"};
/**
* Returns a string representation of this instance, primarily used for
* debugging purposes.
*
* @return A string representation of this instance.
*/
public String toString() {
return "DateTickUnit[" + DateTickUnit.units[this.unit] + ", "
+ this.count + "]";
}
}
| source/org/jfree/chart/axis/DateTickUnit.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* -----------------
* DateTickUnit.java
* -----------------
* (C) Copyright 2000-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Chris Boek;
*
* Changes
* -------
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 27-Nov-2002 : Added IllegalArgumentException to getMillisecondCount()
* method (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 12-Nov-2003 : Added roll fields that can improve the labelling on segmented
* date axes (DG);
* 03-Dec-2003 : DateFormat constructor argument is now filled with an default
* if null (TM);
* 07-Dec-2003 : Fixed bug (null pointer exception) in constructor (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 21-Mar-2007 : Added toString() for debugging (DG);
* 04-Apr-2007 : Added new methods addToDate(Date, TimeZone) and rollDate(Date,
* TimeZone) (CB);
* 09-Jun-2008 : Deprecated addToDate(Date) (DG);
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.jfree.util.ObjectUtilities;
/**
* A tick unit for use by subclasses of {@link DateAxis}. Instances of this
* class are immutable.
*/
public class DateTickUnit extends TickUnit implements Serializable {
/** For serialization. */
private static final long serialVersionUID = -7289292157229621901L;
/** A constant for years. */
public static final int YEAR = 0;
/** A constant for months. */
public static final int MONTH = 1;
/** A constant for days. */
public static final int DAY = 2;
/** A constant for hours. */
public static final int HOUR = 3;
/** A constant for minutes. */
public static final int MINUTE = 4;
/** A constant for seconds. */
public static final int SECOND = 5;
/** A constant for milliseconds. */
public static final int MILLISECOND = 6;
/** The unit. */
private int unit;
/** The unit count. */
private int count;
/** The roll unit. */
private int rollUnit;
/** The roll count. */
private int rollCount;
/** The date formatter. */
private DateFormat formatter;
/**
* Creates a new date tick unit. The dates will be formatted using a
* SHORT format for the default locale.
*
* @param unit the unit.
* @param count the unit count.
*/
public DateTickUnit(int unit, int count) {
this(unit, count, null);
}
/**
* Creates a new date tick unit. You can specify the units using one of
* the constants YEAR, MONTH, DAY, HOUR, MINUTE, SECOND or MILLISECOND.
* In addition, you can specify a unit count, and a date format.
*
* @param unit the unit.
* @param count the unit count.
* @param formatter the date formatter (defaults to DateFormat.SHORT).
*/
public DateTickUnit(int unit, int count, DateFormat formatter) {
this(unit, count, unit, count, formatter);
}
/**
* Creates a new unit.
*
* @param unit the unit.
* @param count the count.
* @param rollUnit the roll unit.
* @param rollCount the roll count.
* @param formatter the date formatter (defaults to DateFormat.SHORT).
*/
public DateTickUnit(int unit, int count, int rollUnit, int rollCount,
DateFormat formatter) {
super(DateTickUnit.getMillisecondCount(unit, count));
this.unit = unit;
this.count = count;
this.rollUnit = rollUnit;
this.rollCount = rollCount;
this.formatter = formatter;
if (formatter == null) {
this.formatter = DateFormat.getDateInstance(DateFormat.SHORT);
}
}
/**
* Returns the date unit. This will be one of the constants
* <code>YEAR</code>, <code>MONTH</code>, <code>DAY</code>,
* <code>HOUR</code>, <code>MINUTE</code>, <code>SECOND</code> or
* <code>MILLISECOND</code>, defined by this class. Note that these
* constants do NOT correspond to those defined in Java's
* <code>Calendar</code> class.
*
* @return The date unit.
*/
public int getUnit() {
return this.unit;
}
/**
* Returns the unit count.
*
* @return The unit count.
*/
public int getCount() {
return this.count;
}
/**
* Returns the roll unit. This is the amount by which the tick advances if
* it is "hidden" when displayed on a segmented date axis. Typically the
* roll will be smaller than the regular tick unit (for example, a 7 day
* tick unit might use a 1 day roll).
*
* @return The roll unit.
*/
public int getRollUnit() {
return this.rollUnit;
}
/**
* Returns the roll count.
*
* @return The roll count.
*/
public int getRollCount() {
return this.rollCount;
}
/**
* Formats a value.
*
* @param milliseconds date in milliseconds since 01-01-1970.
*
* @return The formatted date.
*/
public String valueToString(double milliseconds) {
return this.formatter.format(new Date((long) milliseconds));
}
/**
* Formats a date using the tick unit's formatter.
*
* @param date the date.
*
* @return The formatted date.
*/
public String dateToString(Date date) {
return this.formatter.format(date);
}
/**
* Calculates a new date by adding this unit to the base date, with
* calculations performed in the default timezone and locale.
*
* @param base the base date.
*
* @return A new date one unit after the base date.
*
* @see #addToDate(Date, TimeZone)
*
* @deprecated As of JFreeChart 1.0.10, this method is deprecated - you
* should use {@link #addToDate(Date, TimeZone)} instead.
*/
public Date addToDate(Date base) {
return addToDate(base, TimeZone.getDefault());
}
/**
* Calculates a new date by adding this unit to the base date.
*
* @param base the base date.
* @param zone the time zone for the date calculation.
*
* @return A new date one unit after the base date.
*
* @since 1.0.6
*/
public Date addToDate(Date base, TimeZone zone) {
// as far as I know, the Locale for the calendar only affects week
// number calculations, and since DateTickUnit doesn't do week
// arithmetic, the default locale (whatever it is) should be fine
// here...
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(base);
calendar.add(getCalendarField(this.unit), this.count);
return calendar.getTime();
}
/**
* Rolls the date forward by the amount specified by the roll unit and
* count.
*
* @param base the base date.
* @return The rolled date.
*
* @see #rollDate(Date, TimeZone)
*/
public Date rollDate(Date base) {
return rollDate(base, TimeZone.getDefault());
}
/**
* Rolls the date forward by the amount specified by the roll unit and
* count.
*
* @param base the base date.
* @param zone the time zone.
*
* @return The rolled date.
*
* @since 1.0.6
*/
public Date rollDate(Date base, TimeZone zone) {
// as far as I know, the Locale for the calendar only affects week
// number calculations, and since DateTickUnit doesn't do week
// arithmetic, the default locale (whatever it is) should be fine
// here...
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(base);
calendar.add(getCalendarField(this.rollUnit), this.rollCount);
return calendar.getTime();
}
/**
* Returns a field code that can be used with the <code>Calendar</code>
* class.
*
* @return The field code.
*/
public int getCalendarField() {
return getCalendarField(this.unit);
}
/**
* Returns a field code (that can be used with the Calendar class) for a
* given 'unit' code. The 'unit' is one of: {@link #YEAR}, {@link #MONTH},
* {@link #DAY}, {@link #HOUR}, {@link #MINUTE}, {@link #SECOND} and
* {@link #MILLISECOND}.
*
* @param tickUnit the unit.
*
* @return The field code.
*/
private int getCalendarField(int tickUnit) {
switch (tickUnit) {
case (YEAR):
return Calendar.YEAR;
case (MONTH):
return Calendar.MONTH;
case (DAY):
return Calendar.DATE;
case (HOUR):
return Calendar.HOUR_OF_DAY;
case (MINUTE):
return Calendar.MINUTE;
case (SECOND):
return Calendar.SECOND;
case (MILLISECOND):
return Calendar.MILLISECOND;
default:
return Calendar.MILLISECOND;
}
}
/**
* Returns the (approximate) number of milliseconds for the given unit and
* unit count.
* <P>
* This value is an approximation some of the time (e.g. months are
* assumed to have 31 days) but this shouldn't matter.
*
* @param unit the unit.
* @param count the unit count.
*
* @return The number of milliseconds.
*/
private static long getMillisecondCount(int unit, int count) {
switch (unit) {
case (YEAR):
return (365L * 24L * 60L * 60L * 1000L) * count;
case (MONTH):
return (31L * 24L * 60L * 60L * 1000L) * count;
case (DAY):
return (24L * 60L * 60L * 1000L) * count;
case (HOUR):
return (60L * 60L * 1000L) * count;
case (MINUTE):
return (60L * 1000L) * count;
case (SECOND):
return 1000L * count;
case (MILLISECOND):
return count;
default:
throw new IllegalArgumentException(
"DateTickUnit.getMillisecondCount() : unit must "
+ "be one of the constants YEAR, MONTH, DAY, HOUR, MINUTE, "
+ "SECOND or MILLISECOND defined in the DateTickUnit "
+ "class. Do *not* use the constants defined in "
+ "java.util.Calendar."
);
}
}
/**
* Tests this unit for equality with another object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return <code>true</code> or <code>false</code>.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof DateTickUnit)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
DateTickUnit that = (DateTickUnit) obj;
if (this.unit != that.unit) {
return false;
}
if (this.count != that.count) {
return false;
}
if (!ObjectUtilities.equal(this.formatter, that.formatter)) {
return false;
}
return true;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
public int hashCode() {
int result = 19;
result = 37 * result + this.unit;
result = 37 * result + this.count;
result = 37 * result + this.formatter.hashCode();
return result;
}
/**
* Strings for use by the toString() method.
*/
private static final String[] units = {"YEAR", "MONTH", "DAY", "HOUR",
"MINUTE", "SECOND", "MILLISECOND"};
/**
* Returns a string representation of this instance, primarily used for
* debugging purposes.
*
* @return A string representation of this instance.
*/
public String toString() {
return "DateTickUnit[" + DateTickUnit.units[this.unit] + ", "
+ this.count + "]";
}
}
| Removed tabs.
git-svn-id: ca96c60061366ac92493e2142a352bb838ea8caa@1067 4df5dd95-b682-48b0-b31b-748e37b65e73
| source/org/jfree/chart/axis/DateTickUnit.java | Removed tabs. | <ide><path>ource/org/jfree/chart/axis/DateTickUnit.java
<ide> // number calculations, and since DateTickUnit doesn't do week
<ide> // arithmetic, the default locale (whatever it is) should be fine
<ide> // here...
<del> Calendar calendar = Calendar.getInstance(zone);
<add> Calendar calendar = Calendar.getInstance(zone);
<ide> calendar.setTime(base);
<ide> calendar.add(getCalendarField(this.unit), this.count);
<ide> return calendar.getTime();
<ide> * @see #rollDate(Date, TimeZone)
<ide> */
<ide> public Date rollDate(Date base) {
<del> return rollDate(base, TimeZone.getDefault());
<add> return rollDate(base, TimeZone.getDefault());
<ide> }
<ide>
<ide> /** |
|
Java | agpl-3.0 | 1f6811f72cf2040b46f821baf5b6b784902d64bf | 0 | jpaajarv/parkandrideAPI,jpaajarv/parkandrideAPI,rjokelai/parkandrideAPI,jpaajarv/parkandrideAPI,rjokelai/parkandrideAPI,rjokelai/parkandrideAPI,rjokelai/parkandrideAPI,jpaajarv/parkandrideAPI | // Copyright © 2015 HSL <https://www.hsl.fi>
// This program is dual-licensed under the EUPL v1.2 and AGPLv3 licenses.
package fi.hsl.parkandride.core.domain;
import static java.util.Arrays.asList;
import java.util.List;
public enum CapacityType {
CAR,
DISABLED,
ELECTRIC_CAR,
MOTORCYCLE,
BICYCLE,
BICYCLE_SECURE_SPACE;
public static final CapacityType[] motorCapacities = new CapacityType[]{CAR, ELECTRIC_CAR, MOTORCYCLE, DISABLED};
public static final CapacityType[] bicycleCapacities = new CapacityType[]{BICYCLE, BICYCLE_SECURE_SPACE};
public static final List<CapacityType> motorCapacityList = asList(motorCapacities);
public static final List<CapacityType> bicycleCapacityList = asList(bicycleCapacities);
}
| application/src/main/java/fi/hsl/parkandride/core/domain/CapacityType.java | // Copyright © 2015 HSL <https://www.hsl.fi>
// This program is dual-licensed under the EUPL v1.2 and AGPLv3 licenses.
package fi.hsl.parkandride.core.domain;
import static java.util.Arrays.asList;
import java.util.List;
public enum CapacityType {
CAR,
DISABLED,
ELECTRIC_CAR,
MOTORCYCLE,
BICYCLE,
BICYCLE_SECURE_SPACE;
public static final CapacityType[] motorCapacities = new CapacityType[]{CAR, ELECTRIC_CAR, MOTORCYCLE};
public static final CapacityType[] bicycleCapacities = new CapacityType[]{BICYCLE, BICYCLE_SECURE_SPACE};
public static final List<CapacityType> motorCapacityList = asList(motorCapacities);
public static final List<CapacityType> bicycleCapacityList = asList(bicycleCapacities);
}
| Also disabled cars are counted as motor vehicles
| application/src/main/java/fi/hsl/parkandride/core/domain/CapacityType.java | Also disabled cars are counted as motor vehicles | <ide><path>pplication/src/main/java/fi/hsl/parkandride/core/domain/CapacityType.java
<ide> BICYCLE,
<ide> BICYCLE_SECURE_SPACE;
<ide>
<del> public static final CapacityType[] motorCapacities = new CapacityType[]{CAR, ELECTRIC_CAR, MOTORCYCLE};
<add> public static final CapacityType[] motorCapacities = new CapacityType[]{CAR, ELECTRIC_CAR, MOTORCYCLE, DISABLED};
<ide> public static final CapacityType[] bicycleCapacities = new CapacityType[]{BICYCLE, BICYCLE_SECURE_SPACE};
<ide> public static final List<CapacityType> motorCapacityList = asList(motorCapacities);
<ide> public static final List<CapacityType> bicycleCapacityList = asList(bicycleCapacities); |
|
Java | mit | 7c1025a1b48ae4e6638af4d0fff33f37db6e954d | 0 | byronka/xenos,byronka/xenos,byronka/xenos,byronka/xenos,byronka/xenos,byronka/xenos,byronka/xenos | package com.renomad.qarma;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import com.renomad.qarma.Database_access;
import com.renomad.qarma.Utils;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.PreparedStatement;
public final class Business_logic {
private Business_logic () {
//we don't want anyone instantiating this
//do nothing.
}
/**
* gets a name for display from the user table
*
* @return a string displaying first name, last name, email, or
* null if not found.
*/
public static String get_user_displayname(int user_id) {
String sqlText = "SELECT CONCAT(first_name, ' ',last_name"+
",' (', email,')') as user_displayname "+
"FROM user "+
"WHERE user_id = ?;";
PreparedStatement pstmt = null;
try {
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt( 1, user_id);
ResultSet resultSet = pstmt.executeQuery();
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return null;
}
resultSet.next(); //move to the first set of results.
String display_name = resultSet.getNString("user_displayname");
return display_name;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
public static String get_category_localized(int category_id) {
//for now, there is no localization file, so we'll just include
//the English here.
switch(category_id) {
case 1:
return "math";
case 2:
return "physics";
case 3:
return "economics";
case 4:
return "history";
case 5:
return "english";
default:
return "ERROR";
}
}
public static String[] get_str_array_categories() {
Map<Integer, String> categories = get_all_categories();
java.util.Collection<String> c = categories.values();
String[] cat_array = c.toArray(new String[0]);
return cat_array;
}
/**
* returns a Map of localized categories, indexed by database id.
* @return Map of strings, indexed by id, or null if nothing in db.
*/
public static Map<Integer, String> get_all_categories() {
// 1. set the sql
String sqlText =
"SELECT request_category_id FROM request_category; ";
// 2. set up values we'll need outside the try
PreparedStatement pstmt = null;
try {
// 3. get the connection and set up a statement
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
// 4. execute a statement
ResultSet resultSet = pstmt.executeQuery();
// 5. check that we got results
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return null;
}
// 6. get values from database and convert to an object
//keep adding rows of data while there is more data
Map<Integer, String> categories = new HashMap<Integer,String>();
while(resultSet.next()) {
int rcid = resultSet.getInt("request_category_id");
String category = get_category_localized(rcid);
categories.put(rcid, category);
}
return categories;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* gets an array of categories for a given request
*
*@return an array of Strings, representing the categories, or null if failure.
*/
public static Integer[] get_categories_for_request(int request_id) {
String sqlText =
"SELECT request_category_id "+
"FROM request_to_category "+
"WHERE request_id = ?;";
PreparedStatement pstmt = null;
try {
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt( 1, request_id);
ResultSet resultSet = pstmt.executeQuery();
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return new Integer[0];
}
//keep adding rows of data while there is more data
ArrayList<Integer> categories = new ArrayList<Integer>();
while(resultSet.next()) {
int rcid = resultSet.getInt("request_category_id");
categories.add(rcid);
}
//convert arraylist to array
Integer[] array_of_categories =
categories.toArray(new Integer[categories.size()]);
return array_of_categories;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* Gets a specific Request
*
* @return a single Request
*/
public static Request get_a_request(int request_id) {
String sqlText =
"SELECT request_id, datetime,description,points,"+
"status,title,requesting_user_id "+
"FROM request "+
"WHERE request_id = ?";
PreparedStatement pstmt = null;
try {
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt( 1, request_id);
ResultSet resultSet = pstmt.executeQuery();
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return null;
}
resultSet.next();
int rid = resultSet.getInt("request_id");
String dt = resultSet.getString("datetime");
String d = resultSet.getNString("description");
int p = resultSet.getInt("points");
int s = resultSet.getInt("status");
String t = resultSet.getNString("title");
int ru = resultSet.getInt("requesting_user_id");
Integer[] categories = get_categories_for_request(request_id);
Request request = new Request(rid,dt,d,p,s,t,ru,categories);
return request;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* Gets all the requests for the user.
*
* @return an array of Request
*/
public static Request[] get_all_requests_except_for_user(int user_id) {
String sqlText = "SELECT * FROM request WHERE requesting_user_id <> ?";
PreparedStatement pstmt = null;
try {
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt( 1, user_id);
ResultSet resultSet = pstmt.executeQuery();
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return new Request[0];
}
//keep adding rows of data while there is more data
ArrayList<Request> requests = new ArrayList<Request>();
while(resultSet.next()) {
int rid = resultSet.getInt("request_id");
String dt = resultSet.getString("datetime");
String d = resultSet.getNString("description");
int p = resultSet.getInt("points");
int s = resultSet.getInt("status");
String t = resultSet.getNString("title");
int ru = resultSet.getInt("requesting_user_id");
Request request = new Request(rid,dt,d,p,s,t,ru);
requests.add(request);
}
//convert arraylist to array
Request[] array_of_requests =
requests.toArray(new Request[requests.size()]);
return array_of_requests;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* Gets all the requests for the user.
*
* @return an array of Request
*/
public static Request[] get_requests_for_user(int user_id) {
String sqlText = "SELECT * FROM request WHERE requesting_user_id = ?";
PreparedStatement pstmt = null;
try {
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt( 1, user_id);
ResultSet resultSet = pstmt.executeQuery();
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return new Request[0];
}
//keep adding rows of data while there is more data
ArrayList<Request> requests = new ArrayList<Request>();
while(resultSet.next()) {
int rid = resultSet.getInt("request_id");
String dt = resultSet.getString("datetime");
String d = resultSet.getNString("description");
int p = resultSet.getInt("points");
int s = resultSet.getInt("status");
String t = resultSet.getNString("title");
int ru = resultSet.getInt("requesting_user_id");
Request request = new Request(rid,dt,d,p,s,t,ru);
requests.add(request);
}
//convert arraylist to array
Request[] array_of_requests =
requests.toArray(new Request[requests.size()]);
return array_of_requests;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* given all the data to add a request, does so.
* if any parts fail, this will return false.
* @param user_id the user's id
* @param desc a description string, the core of the request
* @param points the points are the currency for the request
* @param title the short title for the request
* @param categories the various categories for this request,
* provided to us here as a single string.
* Comes straight from the client, we have to parse it.
*/
public static void put_request(
int user_id, String desc, int points,
String title, Integer[] categories) {
String date = Utils.getCurrentDateSqlFormat();
//set up a request object to store this stuff
int status = 1; //always starts open
Request request = new Request(
-1, date, desc, points, status, title, user_id, categories);
//send parsed data to the database
int new_request_id = put_request(request);
if (new_request_id == -1) {
System.err.println(
"error adding request at Business_logic.put_request()");
}
}
/**
* adds a Request to the database
* @param request a request object
* @return the id of the new request. -1 if not successful.
*/
public static int put_request(Request request) {
// 1. set the sql
String update_request_sql =
"INSERT into request (description, datetime, points, " +
"status, title, requesting_user_id) VALUES (?, ?, ?, ?, ?, ?)";
//assembling dynamic SQL to add categories
StringBuilder sb = new StringBuilder("");
sb.append("INSERT into request_to_category ")
.append("(request_id,request_category_id) ")
.append("VALUES (?, ?)");
for (int i = 1; i < request.get_categories().length; i++) {
sb.append(",(?, ?)");
}
String update_categories_sql = sb.toString();
// 2. set up values we'll need outside the try
int result = -1; //default to a guard value that indicates failure
PreparedStatement req_pstmt = null;
PreparedStatement cat_pstmt = null;
Connection conn = null;
try {
//get the connection and set to not auto-commit. Prepare the statements
// 3. get the connection and set up a statement
conn = Database_access.get_a_connection();
conn.setAutoCommit(false);
req_pstmt = conn.prepareStatement(
update_request_sql, Statement.RETURN_GENERATED_KEYS);
cat_pstmt = conn.prepareStatement(
update_categories_sql, Statement.RETURN_GENERATED_KEYS);
// 4. set values into the statement
//set values for adding request
req_pstmt.setString(1, request.description);
req_pstmt.setString( 2, request.datetime);
req_pstmt.setInt( 3, request.points);
req_pstmt.setInt( 4, request.status);
req_pstmt.setString( 5, request.title);
req_pstmt.setInt( 6, request.requesting_user_id);
// 5. execute a statement
//execute one of the updates
result = Database_access.execute_update(req_pstmt);
// 6. check results of statement, if good, continue
// if bad, rollback
//if we get a -1 for our id, the request insert didn't go through.
//so rollback.
if (result < 0) {
System.err.println(
"Transaction is being rolled back for request_id: " + result);
conn.rollback();
return -1;
}
// 7. set values for next statement
//set values for adding categories
for (int i = 0; i < request.categories.length; i++ ) {
int category_id = request.categories[i];
cat_pstmt.setInt( 2*i+1, result);
cat_pstmt.setInt( 2*i+2, category_id);
}
// 8. run next statement
Database_access.execute_update(cat_pstmt);
// 9. commit
conn.commit();
// 10. cleanup and exceptions
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
} finally {
if (conn != null) {
try {
conn.setAutoCommit(true);
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
}
}
Database_access.close_statement(req_pstmt);
Database_access.close_statement(cat_pstmt);
}
return result;
}
/**
* Convert a single string containing multiple categories into
* an array of integers representing those categories.
* the easy way to handle this is to get all the categories and then
* indexof() the string for them.
* @param categories_str a single string that contains 0 or more
* category words, localized. This value comes straight
* unchanged from the client.
* @return an integer array of the applicable categories
*/
public static Integer[] parse_categories_string(String categories_str) {
Map<Integer,String> all_categories = get_all_categories();
//guard clauses
if (all_categories == null) {return new Integer[0];}
if (categories_str == null ||
categories_str.length() == 0) {return new Integer[0];}
String lower_case_categories_str = categories_str.toLowerCase();
ArrayList<Integer> selected_categories = new ArrayList<Integer>();
for (Integer i : all_categories.keySet()) {
String c = get_category_localized(i);
if (lower_case_categories_str.contains(c)) {
selected_categories.add(i);
}
}
Integer[] my_array =
selected_categories.toArray(new Integer[selected_categories.size()]);
return my_array;
}
/**
* given the query string, we will find the proper string
* and convert that to a request, and return that.
*/
public static
Request parse_querystring_and_get_request(String query_string) {
String qs = null;
int request_id = 0;
int value_index = 0;
String request_string = "request=";
final int rsl = request_string.length();
//if we have a query string and it has request= in it.
if ((qs = query_string) != null &&
(value_index = qs.indexOf(request_string)) >= 0) {
request_id = Integer.parseInt(qs.substring(rsl));
}
Request r = get_a_request(request_id);
if (r == null) {
return new Request(0,"","",0,1,"",0);
}
return r;
}
/**
* adds a user. if successful, returns true
*/
public static boolean put_user(
String first_name, String last_name, String email, String password) {
Utils.null_or_empty_string_validation(first_name);
Utils.null_or_empty_string_validation(last_name);
Utils.null_or_empty_string_validation(email);
Utils.null_or_empty_string_validation(password);
User u = new User(first_name, last_name, email, password);
return put_user(u);
}
public static boolean put_user(User user) {
// 1. set the sql
String sqlText =
"INSERT INTO user (first_name, last_name, email, password) " +
"VALUES (?, ?, ?, ?)";
// 2. set up values we'll need outside the try
boolean result = false;
PreparedStatement pstmt = null;
try {
// 3. get the connection and set up a statement
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
// 4. set values into the statement
pstmt.setString( 1, user.first_name);
pstmt.setString( 2, user.last_name);
pstmt.setString( 3, user.email);
pstmt.setString( 4, user.password);
// 5. execute a statement
result = Database_access.execute_update(pstmt) > 0;
// 10. cleanup and exceptions
return result;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return false;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* gets all the current request statuses, like OPEN, CLOSED, and TAKEN
* @return an array of request statuses, or null if failure.
*/
public static Request_status[] get_request_statuses() {
// 1. set the sql
String sqlText =
"SELECT request_status_id, request_status_value FROM request_status;";
// 2. set up values we'll need outside the try
PreparedStatement pstmt = null;
try {
// 3. get the connection and set up a statement
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
// 4. execute a statement
ResultSet resultSet = pstmt.executeQuery();
// 5. check that we got results
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return new Request_status[0];
}
// 6. get values from database and convert to an object
//keep adding rows of data while there is more data
ArrayList<Request_status> statuses =
new ArrayList<Request_status>();
while(resultSet.next()) {
int sid = resultSet.getInt("request_status_id");
String sv = resultSet.getString("request_status_value");
Request_status status = new Request_status(sid,sv);
statuses.add(status);
}
// 7. if necessary, create array of objects for return
//convert arraylist to array
Request_status[] my_array =
statuses.toArray(new Request_status[statuses.size()]);
return my_array;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* Request_status is the enumeration of request statuses.
* It is an immutable object.
* note that the fields are public, but final. Once this object
* gets constructed, there is no changing it. You have to create a
* new one.
*/
public static class Request_status {
public final int status_id;
public final String status_value;
public Request_status ( int status_id, String status_value) {
this.status_id = status_id;
this.status_value = status_value;
}
public String get_status_value() {
//for now, there is no localization file, so we'll just include
//the English here.
switch(status_id) {
case 1:
return "open";
case 2:
return "closed";
case 3:
return "taken";
case 4:
return "ERROR_STATUS_DEV_FIX_ME";
}
return "";
}
}
/**
* User encapsulates the core traits of a user. It is an immutable object.
* note that the fields are public, but final. Once this object
* gets constructed, there is no changing it. You have to create a
* new one.
*/
public static class User {
public final String first_name;
public final String last_name;
public final String email;
public final String password;
public User (
String first_name,
String last_name, String email, String password) {
this.first_name = first_name;
this.last_name = last_name;
this.email = email;
this.password = password;
}
}
/**
* Request encapsulates a user's request. It is an immutable object.
* note that the fields are public, but final. Once this object
* gets constructed, there is no changing it. You have to create a
* new one.
*/
public static class Request {
public final int request_id;
public final String datetime;
public final String description;
public final int points;
public final int status;
public final String title;
public final int requesting_user_id;
private Integer[] categories;
public Request ( int request_id, String datetime, String description,
int points, int status, String title, int requesting_user_id) {
this(request_id, datetime, description, points,
status, title, requesting_user_id, new Integer[0]);
}
public Request ( int request_id, String datetime, String description,
int points, int status, String title, int requesting_user_id,
Integer[] categories) {
this.request_id = request_id;
this.datetime = datetime;
this.description = description;
this.points = points;
this.status = status;
this.title = title;
this.requesting_user_id = requesting_user_id;
this.categories = categories;
}
public Integer[] get_categories() {
Integer[] c = Arrays.copyOf(categories, categories.length);
return c;
}
public String get_status() {
//for now, there is no localization file, so we'll just include
//the English here.
switch(status) {
case 1:
return "open";
case 2:
return "closed";
case 3:
return "taken";
default:
return "ERROR_STATUS_DEV_FIX_ME";
}
}
public String get_categories_string() {
StringBuilder sb = new StringBuilder("");
for (Integer c : categories) {
sb.append(get_category_localized(c)).append(" ");
}
return sb.toString();
}
}
}
| src/com/renomad/qarma/Business_logic.java | package com.renomad.qarma;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import com.renomad.qarma.Database_access;
import com.renomad.qarma.Utils;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.PreparedStatement;
public final class Business_logic {
private Business_logic () {
//we don't want anyone instantiating this
//do nothing.
}
/**
* gets a name for display from the user table
*
* @return a string displaying first name, last name, email, or
* null if not found.
*/
public static String get_user_displayname(int user_id) {
String sqlText = "SELECT CONCAT(first_name, ' ',last_name"+
",' (', email,')') as user_displayname "+
"FROM user "+
"WHERE user_id = ?;";
PreparedStatement pstmt = null;
try {
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt( 1, user_id);
ResultSet resultSet = pstmt.executeQuery();
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return null;
}
resultSet.next(); //move to the first set of results.
String display_name = resultSet.getNString("user_displayname");
return display_name;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
public static String get_category_localized(int category_id) {
//for now, there is no localization file, so we'll just include
//the English here.
switch(category_id) {
case 1:
return "math";
case 2:
return "physics";
case 3:
return "economics";
case 4:
return "history";
case 5:
return "english";
default:
return "ERROR";
}
}
public static String[] get_str_array_categories() {
Map<Integer, String> categories = get_all_categories();
java.util.Collection<String> c = categories.values();
String[] cat_array = c.toArray(new String[0]);
return cat_array;
}
/**
* returns a Map of localized categories, indexed by database id.
* @return Map of strings, indexed by id, or null if nothing in db.
*/
public static Map<Integer, String> get_all_categories() {
// 1. set the sql
String sqlText =
"SELECT request_category_id FROM request_category; ";
// 2. set up values we'll need outside the try
PreparedStatement pstmt = null;
try {
// 3. get the connection and set up a statement
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
// 4. execute a statement
ResultSet resultSet = pstmt.executeQuery();
// 5. check that we got results
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return null;
}
// 6. get values from database and convert to an object
//keep adding rows of data while there is more data
Map<Integer, String> categories = new HashMap<Integer,String>();
while(resultSet.next()) {
int rcid = resultSet.getInt("request_category_id");
String category = get_category_localized(rcid);
categories.put(rcid, category);
}
return categories;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* gets an array of categories for a given request
*
*@return an array of Strings, representing the categories, or null if failure.
*/
public static Integer[] get_categories_for_request(int request_id) {
String sqlText =
"SELECT request_category_id "+
"FROM request_to_category "+
"WHERE request_id = ?;";
PreparedStatement pstmt = null;
try {
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt( 1, request_id);
ResultSet resultSet = pstmt.executeQuery();
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return new Integer[0];
}
//keep adding rows of data while there is more data
ArrayList<Integer> categories = new ArrayList<Integer>();
while(resultSet.next()) {
int rcid = resultSet.getInt("request_category_id");
categories.add(rcid);
}
//convert arraylist to array
Integer[] array_of_categories =
categories.toArray(new Integer[categories.size()]);
return array_of_categories;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* Gets a specific Request for the user.
*
* @return a single Request
*/
public static Request get_a_request(int request_id) {
String sqlText =
"SELECT request_id, datetime,description,points,"+
"status,title,requesting_user_id "+
"FROM request "+
"WHERE request_id = ?";
PreparedStatement pstmt = null;
try {
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt( 1, request_id);
ResultSet resultSet = pstmt.executeQuery();
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return null;
}
resultSet.next();
int rid = resultSet.getInt("request_id");
String dt = resultSet.getString("datetime");
String d = resultSet.getNString("description");
int p = resultSet.getInt("points");
int s = resultSet.getInt("status");
String t = resultSet.getNString("title");
int ru = resultSet.getInt("requesting_user_id");
Integer[] categories = get_categories_for_request(request_id);
Request request = new Request(rid,dt,d,p,s,t,ru,categories);
return request;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* Gets all the requests for the user.
*
* @return an array of Request
*/
public static Request[] get_all_requests_except_for_user(int user_id) {
String sqlText = "SELECT * FROM request WHERE requesting_user_id <> ?";
PreparedStatement pstmt = null;
try {
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt( 1, user_id);
ResultSet resultSet = pstmt.executeQuery();
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return new Request[0];
}
//keep adding rows of data while there is more data
ArrayList<Request> requests = new ArrayList<Request>();
while(resultSet.next()) {
int rid = resultSet.getInt("request_id");
String dt = resultSet.getString("datetime");
String d = resultSet.getNString("description");
int p = resultSet.getInt("points");
int s = resultSet.getInt("status");
String t = resultSet.getNString("title");
int ru = resultSet.getInt("requesting_user_id");
Request request = new Request(rid,dt,d,p,s,t,ru);
requests.add(request);
}
//convert arraylist to array
Request[] array_of_requests =
requests.toArray(new Request[requests.size()]);
return array_of_requests;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* Gets all the requests for the user.
*
* @return an array of Request
*/
public static Request[] get_requests_for_user(int user_id) {
String sqlText = "SELECT * FROM request WHERE requesting_user_id = ?";
PreparedStatement pstmt = null;
try {
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt( 1, user_id);
ResultSet resultSet = pstmt.executeQuery();
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return new Request[0];
}
//keep adding rows of data while there is more data
ArrayList<Request> requests = new ArrayList<Request>();
while(resultSet.next()) {
int rid = resultSet.getInt("request_id");
String dt = resultSet.getString("datetime");
String d = resultSet.getNString("description");
int p = resultSet.getInt("points");
int s = resultSet.getInt("status");
String t = resultSet.getNString("title");
int ru = resultSet.getInt("requesting_user_id");
Request request = new Request(rid,dt,d,p,s,t,ru);
requests.add(request);
}
//convert arraylist to array
Request[] array_of_requests =
requests.toArray(new Request[requests.size()]);
return array_of_requests;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* given all the data to add a request, does so.
* if any parts fail, this will return false.
* @param user_id the user's id
* @param desc a description string, the core of the request
* @param points the points are the currency for the request
* @param title the short title for the request
* @param categories the various categories for this request,
* provided to us here as a single string.
* Comes straight from the client, we have to parse it.
*/
public static void put_request(
int user_id, String desc, int points,
String title, Integer[] categories) {
String date = Utils.getCurrentDateSqlFormat();
//set up a request object to store this stuff
int status = 1; //always starts open
Request request = new Request(
-1, date, desc, points, status, title, user_id, categories);
//send parsed data to the database
int new_request_id = put_request(request);
if (new_request_id == -1) {
System.err.println(
"error adding request at Business_logic.put_request()");
}
}
/**
* adds a Request to the database
* @param request a request object
* @return the id of the new request. -1 if not successful.
*/
public static int put_request(Request request) {
// 1. set the sql
String update_request_sql =
"INSERT into request (description, datetime, points, " +
"status, title, requesting_user_id) VALUES (?, ?, ?, ?, ?, ?)";
//assembling dynamic SQL to add categories
StringBuilder sb = new StringBuilder("");
sb.append("INSERT into request_to_category ")
.append("(request_id,request_category_id) ")
.append("VALUES (?, ?)");
for (int i = 1; i < request.get_categories().length; i++) {
sb.append(",(?, ?)");
}
String update_categories_sql = sb.toString();
// 2. set up values we'll need outside the try
int result = -1; //default to a guard value that indicates failure
PreparedStatement req_pstmt = null;
PreparedStatement cat_pstmt = null;
Connection conn = null;
try {
//get the connection and set to not auto-commit. Prepare the statements
// 3. get the connection and set up a statement
conn = Database_access.get_a_connection();
conn.setAutoCommit(false);
req_pstmt = conn.prepareStatement(
update_request_sql, Statement.RETURN_GENERATED_KEYS);
cat_pstmt = conn.prepareStatement(
update_categories_sql, Statement.RETURN_GENERATED_KEYS);
// 4. set values into the statement
//set values for adding request
req_pstmt.setString(1, request.description);
req_pstmt.setString( 2, request.datetime);
req_pstmt.setInt( 3, request.points);
req_pstmt.setInt( 4, request.status);
req_pstmt.setString( 5, request.title);
req_pstmt.setInt( 6, request.requesting_user_id);
// 5. execute a statement
//execute one of the updates
result = Database_access.execute_update(req_pstmt);
// 6. check results of statement, if good, continue
// if bad, rollback
//if we get a -1 for our id, the request insert didn't go through.
//so rollback.
if (result < 0) {
System.err.println(
"Transaction is being rolled back for request_id: " + result);
conn.rollback();
return -1;
}
// 7. set values for next statement
//set values for adding categories
for (int i = 0; i < request.categories.length; i++ ) {
int category_id = request.categories[i];
cat_pstmt.setInt( 2*i+1, result);
cat_pstmt.setInt( 2*i+2, category_id);
}
// 8. run next statement
Database_access.execute_update(cat_pstmt);
// 9. commit
conn.commit();
// 10. cleanup and exceptions
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
} finally {
if (conn != null) {
try {
conn.setAutoCommit(true);
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
}
}
Database_access.close_statement(req_pstmt);
Database_access.close_statement(cat_pstmt);
}
return result;
}
/**
* Convert a single string containing multiple categories into
* an array of integers representing those categories.
* the easy way to handle this is to get all the categories and then
* indexof() the string for them.
* @param categories_str a single string that contains 0 or more
* category words, localized. This value comes straight
* unchanged from the client.
* @return an integer array of the applicable categories
*/
public static Integer[] parse_categories_string(String categories_str) {
Map<Integer,String> all_categories = get_all_categories();
//guard clauses
if (all_categories == null) {return new Integer[0];}
if (categories_str == null ||
categories_str.length() == 0) {return new Integer[0];}
String lower_case_categories_str = categories_str.toLowerCase();
ArrayList<Integer> selected_categories = new ArrayList<Integer>();
for (Integer i : all_categories.keySet()) {
String c = get_category_localized(i);
if (lower_case_categories_str.contains(c)) {
selected_categories.add(i);
}
}
Integer[] my_array =
selected_categories.toArray(new Integer[selected_categories.size()]);
return my_array;
}
/**
* given the query string, we will find the proper string
* and convert that to a request, and return that.
*/
public static
Request parse_querystring_and_get_request(String query_string) {
String qs = null;
int request_id = 0;
int value_index = 0;
String request_string = "request=";
final int rsl = request_string.length();
//if we have a query string and it has request= in it.
if ((qs = query_string) != null &&
(value_index = qs.indexOf(request_string)) >= 0) {
request_id = Integer.parseInt(qs.substring(rsl));
}
Request r = get_a_request(request_id);
if (r == null) {
return new Request(0,"","",0,1,"",0);
}
return r;
}
/**
* adds a user. if successful, returns true
*/
public static boolean put_user(
String first_name, String last_name, String email, String password) {
Utils.null_or_empty_string_validation(first_name);
Utils.null_or_empty_string_validation(last_name);
Utils.null_or_empty_string_validation(email);
Utils.null_or_empty_string_validation(password);
User u = new User(first_name, last_name, email, password);
return put_user(u);
}
public static boolean put_user(User user) {
// 1. set the sql
String sqlText =
"INSERT INTO user (first_name, last_name, email, password) " +
"VALUES (?, ?, ?, ?)";
// 2. set up values we'll need outside the try
boolean result = false;
PreparedStatement pstmt = null;
try {
// 3. get the connection and set up a statement
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
// 4. set values into the statement
pstmt.setString( 1, user.first_name);
pstmt.setString( 2, user.last_name);
pstmt.setString( 3, user.email);
pstmt.setString( 4, user.password);
// 5. execute a statement
result = Database_access.execute_update(pstmt) > 0;
// 10. cleanup and exceptions
return result;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return false;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* gets all the current request statuses, like OPEN, CLOSED, and TAKEN
* @return an array of request statuses, or null if failure.
*/
public static Request_status[] get_request_statuses() {
// 1. set the sql
String sqlText =
"SELECT request_status_id, request_status_value FROM request_status;";
// 2. set up values we'll need outside the try
PreparedStatement pstmt = null;
try {
// 3. get the connection and set up a statement
Connection conn = Database_access.get_a_connection();
pstmt = conn.prepareStatement(sqlText, Statement.RETURN_GENERATED_KEYS);
// 4. execute a statement
ResultSet resultSet = pstmt.executeQuery();
// 5. check that we got results
if (Database_access.resultset_is_null_or_empty(resultSet)) {
return new Request_status[0];
}
// 6. get values from database and convert to an object
//keep adding rows of data while there is more data
ArrayList<Request_status> statuses =
new ArrayList<Request_status>();
while(resultSet.next()) {
int sid = resultSet.getInt("request_status_id");
String sv = resultSet.getString("request_status_value");
Request_status status = new Request_status(sid,sv);
statuses.add(status);
}
// 7. if necessary, create array of objects for return
//convert arraylist to array
Request_status[] my_array =
statuses.toArray(new Request_status[statuses.size()]);
return my_array;
} catch (SQLException ex) {
Database_access.handle_sql_exception(ex);
return null;
} finally {
Database_access.close_statement(pstmt);
}
}
/**
* Request_status is the enumeration of request statuses.
* It is an immutable object.
* note that the fields are public, but final. Once this object
* gets constructed, there is no changing it. You have to create a
* new one.
*/
public static class Request_status {
public final int status_id;
public final String status_value;
public Request_status ( int status_id, String status_value) {
this.status_id = status_id;
this.status_value = status_value;
}
public String get_status_value() {
//for now, there is no localization file, so we'll just include
//the English here.
switch(status_id) {
case 1:
return "open";
case 2:
return "closed";
case 3:
return "taken";
case 4:
return "ERROR_STATUS_DEV_FIX_ME";
}
return "";
}
}
/**
* User encapsulates the core traits of a user. It is an immutable object.
* note that the fields are public, but final. Once this object
* gets constructed, there is no changing it. You have to create a
* new one.
*/
public static class User {
public final String first_name;
public final String last_name;
public final String email;
public final String password;
public User (
String first_name,
String last_name, String email, String password) {
this.first_name = first_name;
this.last_name = last_name;
this.email = email;
this.password = password;
}
}
/**
* Request encapsulates a user's request. It is an immutable object.
* note that the fields are public, but final. Once this object
* gets constructed, there is no changing it. You have to create a
* new one.
*/
public static class Request {
public final int request_id;
public final String datetime;
public final String description;
public final int points;
public final int status;
public final String title;
public final int requesting_user_id;
private Integer[] categories;
public Request ( int request_id, String datetime, String description,
int points, int status, String title, int requesting_user_id) {
this(request_id, datetime, description, points,
status, title, requesting_user_id, new Integer[0]);
}
public Request ( int request_id, String datetime, String description,
int points, int status, String title, int requesting_user_id,
Integer[] categories) {
this.request_id = request_id;
this.datetime = datetime;
this.description = description;
this.points = points;
this.status = status;
this.title = title;
this.requesting_user_id = requesting_user_id;
this.categories = categories;
}
public Integer[] get_categories() {
Integer[] c = Arrays.copyOf(categories, categories.length);
return c;
}
public String get_status() {
//for now, there is no localization file, so we'll just include
//the English here.
switch(status) {
case 1:
return "open";
case 2:
return "closed";
case 3:
return "taken";
default:
return "ERROR_STATUS_DEV_FIX_ME";
}
}
public String get_categories_string() {
StringBuilder sb = new StringBuilder("");
for (Integer c : categories) {
sb.append(get_category_localized(c)).append(" ");
}
return sb.toString();
}
}
}
| slight tweak to comment
| src/com/renomad/qarma/Business_logic.java | slight tweak to comment | <ide><path>rc/com/renomad/qarma/Business_logic.java
<ide> }
<ide>
<ide> /**
<del> * Gets a specific Request for the user.
<add> * Gets a specific Request
<ide> *
<ide> * @return a single Request
<ide> */ |
|
Java | mit | e949bfd773dc52d163ad0cd3bcfa00483d2dbfb3 | 0 | 15-2505-001-7/eureka | package com.example.v001ff.footmark;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import io.realm.Realm;
public class InputSpotActivity extends AppCompatActivity {
private Realm mRealm; //このオブジェクトはDB更新に使う
EditText mAddPlaceName; //投稿画面の場所の名前入力部分に対応
EditText mAddReview; //投稿画面のレビュー部分に対応
//private Date mDate; //投稿された日時
String latitudeRef; //画像から取得する緯度
String latitude;
String longitudeRef; //画像から取得する経度
String longitude;
Bitmap capturedImage;
//private long AccountID アカウント機能実装後に、投稿したユーザのIDもデータベースに保存する
static final int REQUEST_CAPTURE_IMAGE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_input_spot);
mRealm = Realm.getDefaultInstance();//Realmを使用する準備。Realmクラスのインスタンスを取得している
mAddPlaceName = (EditText) findViewById(R.id.addPlaceName);
mAddReview = (EditText) findViewById(R.id.addReview);
ImageView spot_photo = (ImageView) findViewById(R.id.spot_photo);
spot_photo.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) { //カメラ起動するための処理。試作。
int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
// Android 6.0 のみ、カメラパーミッションが許可されていない場合
final int REQUEST_CODE = 1;
ActivityCompat.requestPermissions(InputSpotActivity.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE); //修正予定ですごめんなさい
if (ActivityCompat.shouldShowRequestPermissionRationale(InputSpotActivity.this, Manifest.permission.CAMERA)) { //修正予定ですごめんなさい
// パーミッションが必要であることを明示するアプリケーション独自のUIを表示
Snackbar.make(view, R.string.rationale, Snackbar.LENGTH_LONG).show();
}
} else {
// 許可済みの場合、もしくはAndroid 6.0以前
// パーミッションが必要な処理。以下でカメラ起動。
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAPTURE_IMAGE);
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(REQUEST_CAPTURE_IMAGE == requestCode && resultCode == Activity.RESULT_OK){
//capturedImage = (Bitmap) data.getExtras().get("data");
//((ImageView) findViewById(R.id.spot_photo)).setImageBitmap(capturedImage);
Bitmap capturedImage = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
capturedImage.compress(Bitmap.CompressFormat.PNG,0,byteArrayStream);
((ImageView) findViewById(R.id.spot_photo)).setImageBitmap(capturedImage);
}
}
public void onPostingButtonTapped(View view) {
//long currentTimeMillis = System.currentTimeMillis();
final Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); //日付の取得(この段階ではString型)
//String dateParse = new String();
//byte[] bytes = MyUtils.getByteFromImage(capturedImage);
try {
//String date2 = df.format(date);
/*ExifInterface exifInterface = new ExifInterface(capturedImage.toString()); //p283にRealmでの画像の扱い方書いてるので参照して修正予定
latitudeRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF); //緯度の取得
latitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
longitudeRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF); //経度の取得
longitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);*/
}
catch (Exception ex) {
ex.printStackTrace();
}
// final String date2 = dateParse.toString();
final String date2 = df.format(date);
mRealm.executeTransaction(new Realm.Transaction(){
@Override
public void execute(Realm realm){
Number maxId = realm.where(FootmarkDataTable.class).max("PlaceId");
long nextId = 0;
if(maxId != null) nextId = maxId.longValue() + 1;
//realm.beginTransaction();
FootmarkDataTable footmarkDataTable = realm.createObject(FootmarkDataTable.class, new Long(nextId));
footmarkDataTable.setPlaceName(mAddPlaceName.getText().toString());
footmarkDataTable.setReviewBody(mAddReview.getText().toString());
//footmarkDataTable.setPlaceDate(date);
//footmarkDataTable.setLatitude(latitude);
//footmarkDataTable.setLongitude(longitude);
//realm.commitTransaction();
}
});
//ここにRealmにデータ追加する文を書く
Toast.makeText(this, "投稿しました!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(InputSpotActivity.this, MainActivity.class));
}
@Override
public void onDestroy() {
super.onDestroy();
mRealm.close(); //投稿画面から離れるときにDBのリソース開放
}
} | Footmark/app/src/main/java/com/example/v001ff/footmark/InputSpotActivity.java | package com.example.v001ff.footmark;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import io.realm.Realm;
public class InputSpotActivity extends AppCompatActivity {
private Realm mRealm; //このオブジェクトはDB更新に使う
EditText mAddPlaceName; //投稿画面の場所の名前入力部分に対応
EditText mAddReview; //投稿画面のレビュー部分に対応
//private Date mDate; //投稿された日時
String latitudeRef; //画像から取得する緯度
String latitude;
String longitudeRef; //画像から取得する経度
String longitude;
Bitmap capturedImage;
//private long AccountID アカウント機能実装後に、投稿したユーザのIDもデータベースに保存する
static final int REQUEST_CAPTURE_IMAGE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_input_spot);
mRealm = Realm.getDefaultInstance();//Realmを使用する準備。Realmクラスのインスタンスを取得している
mAddPlaceName = (EditText) findViewById(R.id.addPlaceName);
mAddReview = (EditText) findViewById(R.id.addReview);
ImageView spot_photo = (ImageView) findViewById(R.id.spot_photo);
spot_photo.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) { //カメラ起動するための処理。試作。
int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
// Android 6.0 のみ、カメラパーミッションが許可されていない場合
final int REQUEST_CODE = 1;
ActivityCompat.requestPermissions(InputSpotActivity.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE); //修正予定ですごめんなさい
if (ActivityCompat.shouldShowRequestPermissionRationale(InputSpotActivity.this, Manifest.permission.CAMERA)) { //修正予定ですごめんなさい
// パーミッションが必要であることを明示するアプリケーション独自のUIを表示
Snackbar.make(view, R.string.rationale, Snackbar.LENGTH_LONG).show();
}
} else {
// 許可済みの場合、もしくはAndroid 6.0以前
// パーミッションが必要な処理。以下でカメラ起動。
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAPTURE_IMAGE);
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(REQUEST_CAPTURE_IMAGE == requestCode && resultCode == Activity.RESULT_OK){
//capturedImage = (Bitmap) data.getExtras().get("data");
//((ImageView) findViewById(R.id.spot_photo)).setImageBitmap(capturedImage);
Bitmap capturedImage = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
capturedImage.compress(Bitmap.CompressFormat.PNG,0,byteArrayStream);
((ImageView) findViewById(R.id.spot_photo)).setImageBitmap(capturedImage);
}
}
public void onPostingButtonTapped(View view) {
//long currentTimeMillis = System.currentTimeMillis();
final Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); //日付の取得(この段階ではString型)
//String dateParse = new String();
//byte[] bytes = MyUtils.getByteFromImage(capturedImage);
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); //日付の取得(この段階ではString型)
//Date dateParse = new Date();
byte[] bytes = MyUtils.getByteFromImage(capturedImage);
try {
//String date2 = df.format(date);
/*ExifInterface exifInterface = new ExifInterface(capturedImage.toString()); //p283にRealmでの画像の扱い方書いてるので参照して修正予定
latitudeRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF); //緯度の取得
latitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
longitudeRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF); //経度の取得
longitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);*/
}
catch (Exception ex) {
ex.printStackTrace();
}
final String date2 = df.format(date);
mRealm.executeTransaction(new Realm.Transaction(){
@Override
public void execute(Realm realm){
Number maxId = realm.where(FootmarkDataTable.class).max("PlaceId");
int nextId = 0;
if(maxId != null) nextId = maxId.intValue() + 1;
//realm.beginTransaction();
FootmarkDataTable footmarkDataTable = realm.createObject(FootmarkDataTable.class, new Long(nextId));
footmarkDataTable.setPlaceName(mAddPlaceName.getText().toString());
footmarkDataTable.setReviewBody(mAddReview.getText().toString());
//footmarkDataTable.setPlaceDate(date);
//footmarkDataTable.setLatitude(latitude);
//footmarkDataTable.setLongitude(longitude);
//footmarkDataTable.setPlaceId(nextId); //PlaceIdを連番で管理
//realm.commitTransaction();
//footmarkDataTable.setReviewDate(sdf.toString();
footmarkDataTable.setReviewDate(date2);
//footmarkDataTable.setLatitude(latitude);
//footmarkDataTable.setLongitude(longitude);
//realm.commitTransaction();
}
});
//ここにRealmにデータ追加する文を書く
Toast.makeText(this, "投稿しました!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(InputSpotActivity.this, MainActivity.class));
}
@Override
public void onDestroy() {
super.onDestroy();
mRealm.close(); //投稿画面から離れるときにDBのリソース開放
}
} | 元に戻した
| Footmark/app/src/main/java/com/example/v001ff/footmark/InputSpotActivity.java | 元に戻した | <ide><path>ootmark/app/src/main/java/com/example/v001ff/footmark/InputSpotActivity.java
<ide> DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); //日付の取得(この段階ではString型)
<ide> //String dateParse = new String();
<ide> //byte[] bytes = MyUtils.getByteFromImage(capturedImage);
<del> //SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); //日付の取得(この段階ではString型)
<del> //Date dateParse = new Date();
<del> byte[] bytes = MyUtils.getByteFromImage(capturedImage);
<ide>
<ide> try {
<ide> //String date2 = df.format(date);
<ide> catch (Exception ex) {
<ide> ex.printStackTrace();
<ide> }
<add> // final String date2 = dateParse.toString();
<ide> final String date2 = df.format(date);
<ide> mRealm.executeTransaction(new Realm.Transaction(){
<ide> @Override
<ide> public void execute(Realm realm){
<ide> Number maxId = realm.where(FootmarkDataTable.class).max("PlaceId");
<del> int nextId = 0;
<del> if(maxId != null) nextId = maxId.intValue() + 1;
<add> long nextId = 0;
<add> if(maxId != null) nextId = maxId.longValue() + 1;
<ide> //realm.beginTransaction();
<ide> FootmarkDataTable footmarkDataTable = realm.createObject(FootmarkDataTable.class, new Long(nextId));
<ide> footmarkDataTable.setPlaceName(mAddPlaceName.getText().toString());
<ide> footmarkDataTable.setReviewBody(mAddReview.getText().toString());
<ide> //footmarkDataTable.setPlaceDate(date);
<del> //footmarkDataTable.setLatitude(latitude);
<del> //footmarkDataTable.setLongitude(longitude);
<del> //footmarkDataTable.setPlaceId(nextId); //PlaceIdを連番で管理
<del> //realm.commitTransaction();
<del> //footmarkDataTable.setReviewDate(sdf.toString();
<del> footmarkDataTable.setReviewDate(date2);
<ide> //footmarkDataTable.setLatitude(latitude);
<ide> //footmarkDataTable.setLongitude(longitude);
<ide> //realm.commitTransaction(); |
|
Java | apache-2.0 | 5e637d504f1142f5ed5df14c3059d5ddb7d66539 | 0 | mikosik/smooth-build,mikosik/smooth-build | package org.smoothbuild.parse;
import static org.smoothbuild.function.base.Name.simpleName;
import static org.smoothbuild.function.base.Type.STRING;
import static org.smoothbuild.parse.ArgumentNodesCreator.createArgumentNodes;
import static org.smoothbuild.parse.LocationHelpers.locationIn;
import static org.smoothbuild.parse.LocationHelpers.locationOf;
import static org.smoothbuild.util.StringUnescaper.unescaped;
import java.util.List;
import java.util.Map;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.smoothbuild.antlr.SmoothParser.ArgContext;
import org.smoothbuild.antlr.SmoothParser.ArgListContext;
import org.smoothbuild.antlr.SmoothParser.CallContext;
import org.smoothbuild.antlr.SmoothParser.ExpressionContext;
import org.smoothbuild.antlr.SmoothParser.FunctionContext;
import org.smoothbuild.antlr.SmoothParser.ParamNameContext;
import org.smoothbuild.antlr.SmoothParser.PipeContext;
import org.smoothbuild.function.base.Function;
import org.smoothbuild.function.base.Name;
import org.smoothbuild.function.base.Param;
import org.smoothbuild.function.base.Signature;
import org.smoothbuild.function.base.Type;
import org.smoothbuild.function.def.DefinedFunction;
import org.smoothbuild.function.def.DefinitionNode;
import org.smoothbuild.function.def.FunctionNode;
import org.smoothbuild.function.def.InvalidNode;
import org.smoothbuild.function.def.StringNode;
import org.smoothbuild.problem.CodeError;
import org.smoothbuild.problem.CodeLocation;
import org.smoothbuild.problem.ProblemsListener;
import org.smoothbuild.util.Empty;
import org.smoothbuild.util.UnescapingFailedException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class DefinedFunctionsCreator {
public static Map<Name, DefinedFunction> createDefinedFunctions(ProblemsListener problems,
SymbolTable symbolTable, Map<String, FunctionContext> functionContexts, List<String> sorted) {
return new Worker(problems, symbolTable, functionContexts, sorted).run();
}
private static class Worker {
private final ProblemsListener problems;
private final SymbolTable symbolTable;
private final Map<String, FunctionContext> functionContexts;
private final List<String> sorted;
private final Map<Name, DefinedFunction> functions = Maps.newHashMap();
public Worker(ProblemsListener problems, SymbolTable symbolTable,
Map<String, FunctionContext> functionContexts, List<String> sorted) {
this.problems = problems;
this.symbolTable = symbolTable;
this.functionContexts = functionContexts;
this.sorted = sorted;
}
public Map<Name, DefinedFunction> run() {
for (String name : sorted) {
DefinedFunction definedFunction = build(functionContexts.get(name));
functions.put(simpleName(name), definedFunction);
}
return functions;
}
public DefinedFunction build(FunctionContext function) {
DefinitionNode node = build(function.pipe());
Type type = node.type();
String name = function.functionName().getText();
ImmutableMap<String, Param> params = Empty.stringParamMap();
Signature signature = new Signature(type, simpleName(name), params);
return new DefinedFunction(signature, node);
}
private DefinitionNode build(PipeContext pipe) {
DefinitionNode result = build(pipe.expression());
List<CallContext> elements = pipe.call();
for (int i = 0; i < elements.size(); i++) {
CallContext call = elements.get(i);
List<Argument> arguments = build(call.argList());
// implicit piped argument's location is set to the pipe character '|'
CodeLocation codeLocation = locationOf(pipe.p.get(i));
arguments.add(new Argument(null, result, codeLocation));
result = build(call, arguments);
}
return result;
}
private DefinitionNode build(ExpressionContext expression) {
if (expression.call() != null) {
return build(expression.call());
}
if (expression.STRING() != null) {
return buildStringNode(expression.STRING());
}
throw new RuntimeException("Illegal parse tree: ExpressionContext without children.");
}
private DefinitionNode build(CallContext call) {
List<Argument> arguments = build(call.argList());
return build(call, arguments);
}
private DefinitionNode build(CallContext call, List<Argument> args) {
String functionName = call.functionName().getText();
Function function = getFunction(functionName);
Map<String, DefinitionNode> explicitArgs = createArgumentNodes(problems, function, args);
if (explicitArgs == null) {
return new InvalidNode(function.type());
} else {
return new FunctionNode(function, explicitArgs);
}
}
private Function getFunction(String functionName) {
// UndefinedFunctionDetector has been run already so we can be sure at
// this
// point that function with given name exists either among imported
// functions or among already handled defined functions.
Function function = symbolTable.getFunction(functionName);
if (function == null) {
return functions.get(simpleName(functionName));
} else {
return function;
}
}
private List<Argument> build(ArgListContext argList) {
List<Argument> result = Lists.newArrayList();
if (argList != null) {
for (ArgContext arg : argList.arg()) {
DefinitionNode node = build(arg.expression());
result.add(new Argument(argName(arg), node, argLocation(arg)));
}
}
return result;
}
private static String argName(ArgContext arg) {
ParamNameContext paramName = arg.paramName();
if (paramName == null) {
return null;
} else {
return paramName.getText();
}
}
private static CodeLocation argLocation(ArgContext arg) {
ParamNameContext paramName = arg.paramName();
if (paramName == null) {
return locationOf(arg.expression());
} else {
return locationOf(paramName);
}
}
private DefinitionNode buildStringNode(TerminalNode stringToken) {
String quotedString = stringToken.getText();
String string = quotedString.substring(1, quotedString.length() - 1);
try {
return new StringNode(unescaped(string));
} catch (UnescapingFailedException e) {
CodeLocation location = locationIn(stringToken.getSymbol(), 1 + e.charIndex());
problems.report(new CodeError(location, e.getMessage()));
return new InvalidNode(STRING);
}
}
}
}
| src/java/org/smoothbuild/parse/DefinedFunctionsCreator.java | package org.smoothbuild.parse;
import static org.smoothbuild.function.base.Name.simpleName;
import static org.smoothbuild.function.base.Type.STRING;
import static org.smoothbuild.parse.ArgumentNodesCreator.createArgumentNodes;
import static org.smoothbuild.parse.LocationHelpers.locationIn;
import static org.smoothbuild.parse.LocationHelpers.locationOf;
import static org.smoothbuild.util.StringUnescaper.unescaped;
import java.util.List;
import java.util.Map;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.smoothbuild.antlr.SmoothParser.ArgContext;
import org.smoothbuild.antlr.SmoothParser.ArgListContext;
import org.smoothbuild.antlr.SmoothParser.CallContext;
import org.smoothbuild.antlr.SmoothParser.ExpressionContext;
import org.smoothbuild.antlr.SmoothParser.FunctionContext;
import org.smoothbuild.antlr.SmoothParser.ParamNameContext;
import org.smoothbuild.antlr.SmoothParser.PipeContext;
import org.smoothbuild.function.base.Function;
import org.smoothbuild.function.base.Name;
import org.smoothbuild.function.base.Param;
import org.smoothbuild.function.base.Signature;
import org.smoothbuild.function.base.Type;
import org.smoothbuild.function.def.DefinedFunction;
import org.smoothbuild.function.def.DefinitionNode;
import org.smoothbuild.function.def.FunctionNode;
import org.smoothbuild.function.def.InvalidNode;
import org.smoothbuild.function.def.StringNode;
import org.smoothbuild.problem.CodeError;
import org.smoothbuild.problem.CodeLocation;
import org.smoothbuild.problem.ProblemsListener;
import org.smoothbuild.util.Empty;
import org.smoothbuild.util.UnescapingFailedException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class DefinedFunctionsCreator {
public static Map<Name, DefinedFunction> createDefinedFunctions(ProblemsListener problems,
SymbolTable symbolTable, Map<String, FunctionContext> functionContexts, List<String> sorted) {
return new Worker(problems, symbolTable, functionContexts, sorted).run();
}
private static class Worker {
private final ProblemsListener problems;
private final SymbolTable symbolTable;
private final Map<String, FunctionContext> functionContexts;
private final List<String> sorted;
private final Map<Name, DefinedFunction> functions = Maps.newHashMap();
public Worker(ProblemsListener problems, SymbolTable symbolTable,
Map<String, FunctionContext> functionContexts, List<String> sorted) {
this.problems = problems;
this.symbolTable = symbolTable;
this.functionContexts = functionContexts;
this.sorted = sorted;
}
public Map<Name, DefinedFunction> run() {
for (String name : sorted) {
DefinedFunction definedFunction = build(functionContexts.get(name));
functions.put(simpleName(name), definedFunction);
}
return functions;
}
public DefinedFunction build(FunctionContext function) {
DefinitionNode node = build(function.pipe());
Type type = node.type();
String name = function.functionName().getText();
ImmutableMap<String, Param> params = Empty.stringParamMap();
Signature signature = new Signature(type, simpleName(name), params);
return new DefinedFunction(signature, node);
}
private DefinitionNode build(PipeContext pipe) {
DefinitionNode result = build(pipe.expression());
List<CallContext> elements = pipe.call();
for (int i = 0; i < elements.size(); i++) {
CallContext call = elements.get(i);
List<Argument> arguments = build(call.argList());
// implicit piped argument's location is set to the pipe character '|'
CodeLocation codeLocation = locationOf(pipe.p.get(i));
arguments.add(new Argument(null, result, codeLocation));
result = build(call, arguments);
}
return result;
}
private DefinitionNode build(ExpressionContext expression) {
if (expression.call() != null) {
return build(expression.call());
}
return buildStringNode(expression.STRING());
}
private DefinitionNode build(CallContext call) {
List<Argument> arguments = build(call.argList());
return build(call, arguments);
}
private DefinitionNode build(CallContext call, List<Argument> args) {
String functionName = call.functionName().getText();
Function function = getFunction(functionName);
Map<String, DefinitionNode> explicitArgs = createArgumentNodes(problems, function, args);
if (explicitArgs == null) {
return new InvalidNode(function.type());
} else {
return new FunctionNode(function, explicitArgs);
}
}
private Function getFunction(String functionName) {
// UndefinedFunctionDetector has been run already so we can be sure at
// this
// point that function with given name exists either among imported
// functions or among already handled defined functions.
Function function = symbolTable.getFunction(functionName);
if (function == null) {
return functions.get(simpleName(functionName));
} else {
return function;
}
}
private List<Argument> build(ArgListContext argList) {
List<Argument> result = Lists.newArrayList();
if (argList != null) {
for (ArgContext arg : argList.arg()) {
DefinitionNode node = build(arg.expression());
result.add(new Argument(argName(arg), node, argLocation(arg)));
}
}
return result;
}
private static String argName(ArgContext arg) {
ParamNameContext paramName = arg.paramName();
if (paramName == null) {
return null;
} else {
return paramName.getText();
}
}
private static CodeLocation argLocation(ArgContext arg) {
ParamNameContext paramName = arg.paramName();
if (paramName == null) {
return locationOf(arg.expression());
} else {
return locationOf(paramName);
}
}
private DefinitionNode buildStringNode(TerminalNode stringToken) {
String quotedString = stringToken.getText();
String string = quotedString.substring(1, quotedString.length() - 1);
try {
return new StringNode(unescaped(string));
} catch (UnescapingFailedException e) {
CodeLocation location = locationIn(stringToken.getSymbol(), 1 + e.charIndex());
problems.report(new CodeError(location, e.getMessage()));
return new InvalidNode(STRING);
}
}
}
}
| added better error handling in DefinedFunctionsCreator
| src/java/org/smoothbuild/parse/DefinedFunctionsCreator.java | added better error handling in DefinedFunctionsCreator | <ide><path>rc/java/org/smoothbuild/parse/DefinedFunctionsCreator.java
<ide> if (expression.call() != null) {
<ide> return build(expression.call());
<ide> }
<del> return buildStringNode(expression.STRING());
<add> if (expression.STRING() != null) {
<add> return buildStringNode(expression.STRING());
<add> }
<add> throw new RuntimeException("Illegal parse tree: ExpressionContext without children.");
<ide> }
<ide>
<ide> private DefinitionNode build(CallContext call) { |
|
Java | mit | c646b20241a3d34685349e188814da62ac559359 | 0 | frank849/LED_synth | import java.lang.*;
import java.util.*;
import java.io.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.filechooser.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import javax.imageio.*;
import java.awt.image.*;
import java.util.zip.*;
import java.util.prefs.Preferences;
public class main_app implements Runnable,ActionListener {
static JFrame main_frame;
static pattern_list_windowc pattern_list_window;
static main_panelc main_panel;
static harmonic_colors_panelc harmonic_colors_panel;
static JFrame harmonic_colors_window;
static hex_keyboard_panelc hex_keyboard_panel;
//static equalizer_windowc equalizer_window;
static bass_treble_windowc bass_treble_window;
static JFrame hex_keyboard_window;
static JMenuBar main_menu_bar;
static song_playerc song_player;
static int sqsize = 32;
static int notes_per_octave = 12;
static int number_of_keys = 120;
//static int num_octaves = 10;
//static int octave_cents = 1200;
static float tempo = 60.0f;
//static int scale[];
//static int octave_offset = 0;
static int base_freq = 16;
static int wolf_fifth_cents = 0;
static pattern_playerc pattern_player;
static int ID_NUM = 244368531;
static int pan_note = 2;
static JLabel status_bar;
static boolean song_modified = false;
static HashMap pattern_list;
static HashMap tuning_map;
static Vector song_list;
static int PATTERN_MODE = 0;
static int SONG_MODE = 1;
static int NOTE_MODE = 2;
static int play_mode = SONG_MODE;
static options_dialogc options_dialog;
//static new_song_dialogc new_song_dialog;
static new_song_wizardc new_song_wizard;
static JScrollPane main_panel_scroller;
static wave_writerc wave_writer;
static tunning_table_windowc tunning_table_window;
static string_table_options_dialogc string_table_options_dialog;
static TextTransferc TextTransfer;
static Preferences prefs;
static export_wave_dialogc export_wave_dialog;
static envelope_dialogc envelope_dialog;
static short primes_table75[];
//static short primes_table75[] = {2};
//static short primes_table75[] =
//{2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97};
static prime_listc prime_list; //= new prime_listc(9);
static prime_table_windowc prime_table_window = null;
//static int harmonic_pos[] = new int[4];
static create_temperament_dialog CT_dialog;
static double get_centsf(float f) {
return (((Math.log(f) / Math.log(2)) * 1200)+0.5);
}
static int get_num_steps_from_cents(int c) {
double f1 = c;
f1 = f1 * main_app.notes_per_octave;
double f2 = song_player.scale.interval_size;
double f3 = f1/f2;
if (f3 < 0) {
return (int) (f3-0.5);
}
return (int) (f3+0.5);
}
void add_random_melody() {
patternc p = main_app.song_player.pattern;
Random rand = new Random();
Rectangle r = main_panel_scroller.getViewport().getViewRect();
int y2 = r.y / sqsize;
int h = r.height / sqsize;
for (int x = 0;x < p.length;x++) {
int y = rand.nextInt(h)+y2;
int a = p.get_cell(x,y);
p.set_cell(x,y,a ^ pan_note);
}
main_frame.repaint();
}
void display_song_length() {
int total_length = 0;
for (int i = 0;i < song_list.size();i++) {
song_list_entryc e = (song_list_entryc) song_list.get(i);
patternc pat = (patternc) pattern_list.get(e.pattern);
total_length = total_length + pat.length;
}
float f = total_length;
f = (f / tempo) * 60.0f;
int minutes = (int) (f / 60);
int seconds = (((int) f ) % 60);
JOptionPane.showMessageDialog(main_frame,"this song is " + minutes + " minutes and " + seconds + " seconds long","info",JOptionPane.INFORMATION_MESSAGE);
}
void add_random_patterns() {
String msg = "how many patterns to add?";
String number_string = JOptionPane.showInputDialog(main_frame,msg,"10");
if (number_string == null) {return;}
Random rand = new Random();
try {
int n = Integer.parseInt(number_string);
Set s = pattern_list.keySet();
Object pnames[] = s.toArray();
int psize = s.size();
s = tuning_map.keySet();
Object tnames[] = s.toArray();
int tsize = s.size();
int os = song_player.scale.interval_size;
for (int i = 0;i < n;i++) {
String pname = (String) pnames[rand.nextInt(psize)];
String tname = (String) tnames[rand.nextInt(tsize)];
int m = rand.nextInt(notes_per_octave);
m = m - (notes_per_octave >> 1);
int c = (-m * os) / notes_per_octave;
c = c + rand.nextInt(os) - (os >> 1);
double k = scalec.cents_to_key(c);
k = Math.rint(k);
c = scalec.key_to_cents(k);
//k = k + rand.nextInt(1200)-600;
//int ed = scalec.equal_divisions;
//int d = rand.nextInt(ed) - (ed >> 1);
//d = d - (notes_per_octave >> 1);
//k = k + scalec.key_to_cents(d);
song_list.add(new song_list_entryc(pname,m,c,tname));
}
} catch (java.lang.NumberFormatException e) {
JOptionPane.showMessageDialog(main_frame,
"invalid number","error",
JOptionPane.ERROR_MESSAGE);
}
pattern_list_window.update_list_box();
//pattern_list_window.update_list_box();
}
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
patternc pattern = song_player.pattern;
if (action.equals("menu_new")) {
if (main_app.song_modified == true) {
main_app.save_song_prompt();
}
//new_song_dialog.show();
new_song_wizard.show();
}
if (action.equals("edit_harmonic_colors")) {
harmonic_colors_window.show();
}
if (action.equals("menu_open_wave")) {
load_instrument_as_wave();
}
if (action.equals("menu_open")) {
open2();
}
if (action.equals("menu_save")) {
save2();
}
if (action.equals("menu_export_wave")) {
export_wave();
}
if (action.equals("menu_options")) {
options_dialog.show();
}
if (action.equals("menu_exit")) {
exit2();
}
if (action.equals("str_table_options")) {
string_table_options_dialog.show();
}
if (action.equals("menu_add_pattern")) {
patternc p = pattern_list_model.create_new_pattern(main_frame);
if (p != null) {
pattern_list_window.add_to_song_list(p.name);
}
}
if (action.equals("double_length")) {
pattern.double_length();
main_panel.repaint();
main_app.update_status_bar();
}
if (action.equals("triple_length")) {
pattern.triple_length();
main_panel.repaint();
main_app.update_status_bar();
}
if (action.equals("transpose_fifth_up")) {
JOptionPane.showMessageDialog(main_frame,
"transpose_fifth_up is obsolete",
"error",
JOptionPane.ERROR_MESSAGE);
//pattern.transpose_fifth_up();
main_panel.repaint();
}
if (action.equals("transpose_fourth_down")) {
JOptionPane.showMessageDialog(main_frame,
"transpose_fourth_down is obsolete",
"error",
JOptionPane.ERROR_MESSAGE);
//pattern.transpose_fourth_down();
main_panel.repaint();
}
if (action.equals("menu_pattern_list")) {
pattern_list_window.show();
}
if (action.equals("menu_copy")) {
String str = pattern.write_to_string();
TextTransfer.setClipboardContents(str);
}
if (action.equals("menu_paste")) {
String str = TextTransfer.getClipboardContents();
patternc p = patternc.read_pattern_from_string(str);
if (p != null) {
pattern_list_model.add_pattern(p);
pattern_list_window.add_to_song_list(p.name);
pattern = p;
}
}
//if (action.equals("add_random_patterns")) {
// add_random_patterns();
//}
if (action.equals("menu_rename")) {
String msg = "enter a new name for the pattern";
String new_string = JOptionPane.showInputDialog(main_frame,msg,pattern.name);
if (new_string != null) {
pattern_list_window.update_pattern_name(new_string);
pattern.name = new_string;
}
}
if (action.equals("edit_envelope")) {
envelope_dialog.show();
}
if (action.equals("bass_treble")) {
if (bass_treble_window == null) {
bass_treble_window = new bass_treble_windowc();
}
bass_treble_window.show();
}
//if (action.equals("equalizer")) {
// if (equalizer_window == null) {
// equalizer_window = new equalizer_windowc();
// }
// equalizer_window.show();
//}
if (action.equals("show_hex_keyboard")) {
hex_keyboard_window.show();
}
if (action.equals("get_song_length")) {
display_song_length();
}
if (action.equals("add_random_patterns")) {
add_random_patterns();
}
if (action.equals("add_random_melody")) {
add_random_melody();
}
if (action.equals("view_prime_table")) {
if (prime_table_window == null) {
prime_table_window = new prime_table_windowc();
}
prime_table_window.show();
}
if (action.equals("view_tunning_table")) {
tunning_table_window.show();
}
if (action.equals("create_temperament")) {
create_temperament_dialog d = new create_temperament_dialog(main_frame,"create temperament");
d.show();
if (d.OK_Clicked()) {
//double cents = d.get_offset();
//double generator = d.get_generator_cents();
//int octave_cents = main_app.octave_cents;
//double ed = scalec.equal_divisions;
//Double s[] = new Double[notes_per_octave];
//for (int i = 0;i < notes_per_octave;i++) {
// s[i] = new Double( cents);
// cents = cents + generator;
// if (cents > ed) {cents = cents - ed;}
//}
//Arrays.sort(s);
//for (int i = 0;i < notes_per_octave;i++) {
// tunning_table_window.spinner[i].setValue(s[i]);
//}
song_player.scale.init();
tunning_table_window.update();
//System.out.println("OK_Clicked");
}
}
if (action.equals("generate_mean_tone_scale")) {
JOptionPane.showMessageDialog(main_frame,
"generate_mean_tone_scale is obsolete",
"error",
JOptionPane.ERROR_MESSAGE);
}
/*
if (action.equals("generate_mean_tone_scale")) {
generate_mean_tone_scale_dialog d = new generate_mean_tone_scale_dialog(main_frame,"generate mean tone scale");
d.show();
if (d.OK_Clicked()) {
//int octave_cents = main_app.octave_cents;
int start = d.get_start_note();
int step = d.get_step_value();
double interval = d.get_interval();
byte a[] = new byte[notes_per_octave];
int i = start;
double cents = song_player.scale.get(start);
while (a[i] != 32) {
a[i] = 32;
tunning_table_window.spinner[i].setValue(new Integer((int) cents));
cents = cents + interval;
if (cents > octave_cents) {cents = cents - octave_cents;}
i = (i + step) % notes_per_octave;
}
}
}
*/
if (action.equals("import_scala")) {
import_scala();
}
if (action.equals("export_scala")) {
export_scala();
}
}
static void import_scala() {
try{
FileDialog f = new FileDialog(main_frame,"import scala",FileDialog.LOAD);
f.show();
if (f.getFile() != null) {
String filename = f.getDirectory() + f.getFile();
scl_file sf = new scl_file();
sf.read_table(filename,song_player.scale);
tunning_table_window.update();
}
} catch (Exception err) {
System.out.println("menusave error");
System.out.println(err.getMessage());
err.printStackTrace();
}
}
static void export_scala() {
try{
FileDialog f = new FileDialog(main_frame,"export scala",FileDialog.SAVE);
f.show();
if (f.getFile() != null) {
String title = JOptionPane.showInputDialog("Enter a title for this scale");
if (title != null) {
File f2 = new File(f.getDirectory() + f.getFile());
if (f2.exists() == false) {
scl_file sf = new scl_file();
sf.write_table(f.getDirectory(),f.getFile(),title,song_player.scale);
tunning_table_window.update();
} else {
JOptionPane.showMessageDialog(main_frame,new JLabel("file already exists"),"error",JOptionPane.ERROR_MESSAGE);
}
}
}
} catch (Exception err) {
System.out.println("menusave error");
System.out.println(err.getMessage());
err.printStackTrace();
}
}
static void export_wave() {
try{
//FileDialog f = new FileDialog(main_frame,"export to wave",FileDialog.SAVE);
//System.out.println("tmp: " + System.getProperty("java.io.tmpdir"));
//String tmp_dir = System.getProperty("java.io.tmpdir");
//String tmp_dir = "";
String tmp_dir = prefs.get("export_wave_directory",main_panelc.dirname);
JFileChooser fc = new JFileChooser();
fc.setSelectedFile(new File(tmp_dir,"output90613708930439146539.wav"));
int r = fc.showDialog(main_frame,"export to wave");
//f.setDirectory(main_panelc.dirname);
//f.setFile("output90613708930439146539.wav");
//f.show();
if (r == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
//String filename = f.getDirectory() + f.getFile();
String filename = f.getParent() + File.separator + f.getName();
prefs.put("export_wave_directory",f.getParent());
System.out.println(filename);
//pattern_list_window.table.changeSelection(0,0,false,false);
boolean b = wave_writerc.read_wave_id(new File(filename));
if (b == true) {
if (export_wave_dialog == null) {
export_wave_dialog = new export_wave_dialogc(main_frame);
}
export_wave_dialogc d = export_wave_dialog;
d.setVisible(true);
if (d.ok_clicked) {
Number n = null;
n = (Number) d.fade_in_spinner.getValue();
float fi = n.floatValue();
n = (Number) d.fade_out_spinner.getValue();
float fo = n.floatValue();
boolean st = d.op_stereo.isSelected();
boolean sh = d.op_16bit.isSelected();
prefs.putBoolean("wave_stereo",st);
prefs.putBoolean("wave_16bit",sh);
prefs.putDouble("wave_fade_in",fi);
prefs.putDouble("wave_fade_out",fo);
main_app.wave_writer = new wave_writerc(filename,st,sh,fi,fo);
main_app.wave_writer.write_song();
main_app.wave_writer.close();
}
} else {
JOptionPane.showMessageDialog(main_frame,"error: file already exists","error",JOptionPane.ERROR_MESSAGE);
}
}
} catch (Exception err) {
System.out.println("menusave error");
System.out.println(err.getMessage());
err.printStackTrace();
}
}
static int save_song_prompt() {
int op = JOptionPane.showConfirmDialog(main_frame,
"Do you want to save your song?","save song?",
JOptionPane.YES_NO_OPTION);
if (op == JOptionPane.YES_OPTION) {
save2();
}
return op;
}
static void exit2() {
try{
while (main_app.song_modified == true) {
int old_vol = pattern_player.volume;
pattern_player.volume = 0;
int op = save_song_prompt();
if (op == JOptionPane.NO_OPTION) {
System.exit(0);
}
}
System.exit(0);
} catch(SecurityException err){
System.out.println("can not exit");
}
}
static void update_status_bar() {
String str = "volume: " + pattern_player.volume + "dB";
//str = str + " bass: " + pattern_player.bass;
//int o = num_octaves-octave_offset;
str = str + " pan: ";
if (pan_note == 1) {str = str + "left";}
if (pan_note == 2) {str = str + "center";}
if (pan_note == 3) {str = str + "right";}
if (play_mode == PATTERN_MODE) {str = str + " mode: P ";}
if (play_mode == SONG_MODE) {str = str + " mode: S ";}
if (play_mode == NOTE_MODE) {str = str + " mode: N ";}
str = str + " length: " + song_player.pattern.get_length();
int sh = main_panelc.sel_harmonic;
int h = (int)((main_panelc.harmonic_low[sh]*10)+0.5);
str = str + " harmonic: ";
str = str + ((int) (h/10)) + ".";
str = str + ((int) (h%10));
status_bar.setText(str);
}
static void open2() {
try{
FileDialog f = new FileDialog(main_frame,"open pattern",FileDialog.LOAD);
main_panelc.dirname = prefs.get("song_directory",main_panelc.dirname);
//System.out.println(main_panelc.dirname);
f.setDirectory(main_panelc.dirname);
//f.setDirectory("a3928798237");
f.show();
if (f.getFile() != null) {
String filename = f.getDirectory() + f.getFile();
int ft = get_file_type(filename);
if (ft == 1) {
DataInputStream infile = new DataInputStream(new BufferedInputStream(
new GZIPInputStream(new FileInputStream(filename))));
open_file(infile);
} else if (ft == 2) {
new song_browserc(filename);
} else {
JOptionPane.showMessageDialog(main_frame,
"error: invalid gz file","can not open file",
JOptionPane.ERROR_MESSAGE);
}
main_panel.repaint();
main_panelc.filename = f.getFile();
main_panelc.dirname = f.getDirectory();
prefs.put("song_directory",main_panelc.dirname);
}
} catch (Exception err) {
System.out.println("menuopen error");
System.out.println(err.getMessage());
err.printStackTrace();
}
}
static void save2() {
try{
FileDialog f = new FileDialog(main_frame,"save pattern",FileDialog.SAVE);
main_panelc.dirname = prefs.get("song_directory",null);
f.setDirectory(main_panelc.dirname);
//f.setFile(main_panelc.filename);
f.show();
if (f.getFile() != null) {
String filename = f.getDirectory() + f.getFile();
File f2 = new File(filename);
String filename2 = main_panelc.dirname;
filename2 = filename2 + main_panelc.filename;
if ((f2.exists() == false) | (filename.equals(filename2)) == true) {
save_file(filename);
main_panelc.filename = f.getFile();
main_panelc.dirname = f.getDirectory();
prefs.put("song_directory",main_panelc.dirname);
} else {
JOptionPane.showMessageDialog(main_frame,new JLabel("file already exists"),"error",JOptionPane.ERROR_MESSAGE);
}
}
} catch (Exception err) {
System.out.println("menusave error");
System.out.println(err.getMessage());
err.printStackTrace();
}
}
static int get_file_type(String filename) {
try {
byte b[] = new byte[4];
InputStream in = new FileInputStream(filename);
in.read(b);
//System.out.println("bytes: " + b[0] + " " + b[1] + " " + b[2] + " " + b[3]);
if ((b[0] == 31) & (b[1] == -117) & (b[2] == 8) & (b[3] == 0)) {
return 1;
}
if ((b[0] == 0x50) & (b[1] == 0x4b) & (b[2] == 0x03) & (b[3] == 0x04)) {
return 2;
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
static boolean isColorDark(int col) {
int a = (col&255)+((col>>8)&255)+((col>>16)&255);
if (a < 384) {return true;}
return false;
}
static Color get_text_color(Color col) {
return get_text_color(color_to_int(col));
}
static Color get_text_color(int col) {
if (isColorDark(col) == true) {
return Color.white;
} else {
return Color.black;
}
}
static int color_to_int(Color col) {
int red = col.getRed();
int green = col.getGreen();
int blue = col.getBlue();
return red + (green << 8) + (blue << 16);
}
static Color int_to_color(int col) {
int red = col & 255;
int green = (col >> 8) & 255;
int blue = (col >> 16) & 255;
return new Color(red,green,blue);
}
static void open_file(DataInputStream infile) {
try {
int id = infile.readInt();
if (id != ID_NUM) {
JOptionPane.showMessageDialog(main_frame,
"error: invalid gz file",
"can not open file",
JOptionPane.ERROR_MESSAGE);
return;
}
int version = infile.readUnsignedShort();
if ((version < 0) | (version >= 9)) {
JOptionPane.showMessageDialog(main_frame,
"error: the file is too new",
"can not open file",
JOptionPane.ERROR_MESSAGE);
return;
}
main_panelc.song_pos = -1;
notes_per_octave = infile.readUnsignedByte();
if ((notes_per_octave == 0) & (version >= 8)) {
notes_per_octave = 256;
}
scalec.equal_divisions = (short) notes_per_octave;
scalec.period = (short) notes_per_octave;
//scale = new int[notes_per_octave];
scalec scale = new scalec(notes_per_octave);
song_player.scale = scale;
if (version >= 8) {
number_of_keys = infile.readInt();
} else {
int num_octaves = infile.readUnsignedByte();
number_of_keys = num_octaves*notes_per_octave;
}
int num_patterns = 0;
if (version >= 1) {num_patterns = infile.readInt();}
else {num_patterns = infile.readUnsignedByte()+1;}
int num_primes = infile.readUnsignedByte();
prime_list = new prime_listc(num_primes);
base_freq = infile.readUnsignedShort();
int song_length = infile.readInt();
int num_extra_bytes = 0;
Vector pattern_name_list = new Vector();
if (version >= 7) {
song_playerc.highest_note_freq = infile.readInt();
if (version >= 8) {
infile.readInt();
} else {
int sample_rate = infile.readInt();
if (pattern_playerc.sample_rate != sample_rate) {
equalizer.sample_rate_changed();
pattern_playerc.sample_rate = sample_rate;
}
}
equalizer e2 = equalizer.e2;
e2.read(infile,version);
equalizer.e1.copy(e2);
equalizer.e3.copy(e2);
infile.readShort();
if (version >= 8) {
infile.readByte();
} else {
sampleplayerc.interpolation = infile.readByte();
}
if (bass_treble_window != null) {
bass_treble_window.update();
}
}
if (version >= 4) {
infile.readByte();
if (version >= 6) {
infile.readInt();
infile.readInt();
}
num_extra_bytes = infile.readInt();
//System.out.println(num_extra_bytes);
if (version <= 7) {
scalec.interval_size = infile.readShort() << 16;
}
tempo = infile.readFloat();
main_panelc.harmonic_color.clear();
int nh = infile.readInt();
for (int i = 0;i < nh;i++) {
main_panelc.harmonic_color.add(int_to_color(infile.readInt()));
}
//System.out.println("num_extra_bytes: " + num_extra_bytes);
if (num_extra_bytes >= 10) {
num_extra_bytes = num_extra_bytes - 10;
int b = infile.readByte();
pattern_player.ins.string_table_num_octaves = b;
//System.out.println("num_octaves: " + b);
b = infile.readByte();
if (version <= 7) {b = b+b+20;}
int minSize = string_table_options_dialogc.minSize;
int maxSize = string_table_options_dialogc.maxSize;
if (b < minSize) {b = minSize;}
if (b > maxSize) {b = maxSize;}
pattern_player.ins.string_table_psize = b;
//System.out.println("table_psize: " + b);
int s = infile.readInt();
pattern_player.ins.string_table_seed = s;
//System.out.println("seed: " + s);
float bandwidth = infile.readFloat();
pattern_player.ins.bandwidth = bandwidth;
//System.out.println("bandwidth: " + bandwidth);
if (num_extra_bytes >= 4) {
num_extra_bytes = num_extra_bytes - 4;
hex_keyboard_panelc.x_step = infile.readShort();
hex_keyboard_panelc.y_step = infile.readShort();
if (num_extra_bytes >= 16) {
num_extra_bytes = num_extra_bytes - 16;
sampleplayerc.envelope.read(infile);
}
}
}
}
//num_extra_bytes = num_extra_bytes + 2;
//System.out.println(num_extra_bytes);
for (int i = 0;i < num_extra_bytes;i++) {
infile.readUnsignedByte();
}
if (version >= 8) {
scalec.interval_size = infile.readInt();
//System.out.println("interval_size: " + scalec.interval_size);
scalec.equal_divisions = infile.readUnsignedShort();
//System.out.println("equal_divisions: " + scalec.equal_divisions);
scalec.generator = infile.readFloat();
//System.out.println("generator: " + scalec.generator);
scalec.period = infile.readFloat();
//System.out.println("period: " + scalec.period);
}
if (version == 3) {
infile.readByte();
int header_size = 32;
int header_size2 = infile.readInt();
num_extra_bytes = header_size2-header_size;
scalec.interval_size = infile.readShort() << 16;
tempo = infile.readFloat();
}
if (version < 3) {
if (version >= 1) {
infile.readInt();infile.readInt();
infile.readInt();infile.readInt();
}
infile.readInt();infile.readInt();
infile.readInt();infile.readShort();
}
song_list.clear();
pattern_list.clear();
tuning_map.clear();
//System.out.println("tunings ");
if (version >= 3) {
if (version >= 6) {
int num_tunings = infile.readInt();
for (int i = 0;i < num_tunings;i++) {
scale = new scalec(notes_per_octave);
String tuning_name = infile.readUTF();
//System.out.println("tuning: " + tuning_name);
if (version >= 8) {
for (int j = 0;j < notes_per_octave;j++) {
scale.scale[j] = infile.readInt();
}
} else {
for (int j = 0;j < notes_per_octave;j++) {
scale.scale[j] = infile.readShort() << 16;
}
}
tuning_map.put(tuning_name,scale);
}
} else {
for (int i = 0;i < notes_per_octave;i++) {
scale.scale[i] = infile.readShort() << 16;
}
tuning_map.put("t",scale);
}
}
if (version >= 8) {
prime_list.read_list(infile);
} else {
for (int i = 0;i < prime_list.num_primes;i++) {
prime_list.prime_factor[i] = infile.readFloat();
}
}
for (int i = 0;i < num_patterns;i++) {
int length = infile.readUnsignedShort();
//System.out.println("length: " + length);
patternc pattern = new patternc(length);
song_player.pattern = pattern;
if (version >= 1) {
pattern.name = infile.readUTF();
if (version >= 6) {
for (int j = 0;j < ((notes_per_octave>>3)+1);j++) {
pattern.scale[j] = infile.readByte();
}
}
int b = infile.readShort();
if ((b & 1) == 1) {
pattern.image = infile.readUTF();
}
infile.readShort();
infile.readInt();
infile.readInt();
infile.readInt();
infile.readInt();
} else {
pattern.name = "pattern";
}
for (int x = 0;x < pattern.length;x++) {
int n = number_of_keys;
if (version == 0) {n = n - 1;}
for (int y = 0;y <= n;y++) {
int a = infile.readByte();
pattern.set_cell(x,y,a);
}
}
String patternname2 = pattern.name;
int x = 2;
while (pattern_list.get(patternname2) != null) {
patternname2 = pattern.name + x;
x = x + 1;
}
pattern_list.put(patternname2,pattern);
if (version <= 4) {
pattern_name_list.add(patternname2);
}
}
//pattern_player.volume = 1;
for (int i = 0;i < song_length;i++) {
String pat_name;
if (version >= 5) {
pat_name = infile.readUTF();
} else {
int i2 = infile.readInt();
pat_name = (String) pattern_name_list.get(i2);
}
patternc p = (patternc) main_app.pattern_list.get(pat_name);
song_list_entryc en = new song_list_entryc(pat_name,0,0,"t");
main_app.song_list.add(en);
if (version >= 2) {
if (version >= 8) {
en.cents = infile.readInt();
} else {
en.cents = infile.readShort() << 16;
}
en.mode = infile.readByte();
infile.readByte();
}
if (version >= 6) {
en.tuning = infile.readUTF();
}
}
//pattern_list_model.update_pattern_list_ids();
pattern_list_window.update_list_box();
main_app.song_modified = false;
main_app.main_panel.update_size();
main_app.song_player.create_players();
//main_panelc.setup_scale34(main_app.notes_per_octave);
tunning_table_window.create_new_panel();
if (prime_table_window != null) {
prime_table_window.create_new_panel();
}
main_panelc.update_harmonics();
//main_panelc.update_harmonic_offsets();
//main_app.pattern_player.alloc_string_tables(6);
//main_app.pattern_player.update_players();
//if (main_app.song_list.size() > 0) {
// pattern_list_window.table.setSelectedRow(0);
//}
main_app.pattern_list_window.play_next_pattern();
infile.close();
update_status_bar();
} catch (Exception e) {
e.printStackTrace();
}
}
static void save_file(String filename) {
try {
main_app.song_modified = false;
DataOutputStream outfile = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(filename))));
outfile.writeInt(ID_NUM); //ID
outfile.writeShort(8); //Version
outfile.writeByte(notes_per_octave);
//int bn = patternc.black_notes_per_octave;
//outfile.writeByte(bn);
//outfile.writeByte(num_octaves);
outfile.writeInt(number_of_keys);
outfile.writeInt(pattern_list.size());//num patterns
outfile.writeByte(prime_list.num_primes);
outfile.writeShort(base_freq);
outfile.writeInt(song_list.size());//song length
outfile.writeInt(song_playerc.highest_note_freq);
outfile.writeInt(0);
equalizer.e2.write(outfile);
outfile.writeShort(0);
outfile.writeByte(0);
outfile.writeByte(0);
outfile.writeInt(0);
outfile.writeInt(0);
outfile.writeInt(30);//extra bytes
outfile.writeFloat(tempo);
outfile.writeInt(main_panelc.harmonic_color.size());
for (int i = 0;i < main_panelc.harmonic_color.size();i++) {
Color c = (Color) main_panelc.harmonic_color.get(i);
outfile.writeInt(color_to_int(c));
}
int b = 0;
b = pattern_player.ins.string_table_num_octaves;
outfile.writeByte(b);
b = pattern_player.ins.string_table_psize;
outfile.writeByte(b);
int seed = pattern_player.ins.string_table_seed;
outfile.writeInt(seed);
float bandwidth = pattern_player.ins.bandwidth;
outfile.writeFloat(bandwidth);
int x_step = hex_keyboard_panelc.x_step;
outfile.writeShort(x_step);
int y_step = hex_keyboard_panelc.y_step;
outfile.writeShort(y_step);
sampleplayerc.envelope.write(outfile);
outfile.writeInt(scalec.interval_size);
outfile.writeShort(scalec.equal_divisions);
outfile.writeFloat((float) scalec.generator);
outfile.writeFloat((float) scalec.period);
//for (int i = 0;i < notes_per_octave;i++) {
// outfile.writeShort(scale.get(i));
//}
outfile.writeInt(tuning_map.size());
Set ks = tuning_map.keySet();
for (Iterator it = ks.iterator();it.hasNext();) {
String tuning_name = (String) it.next();
scalec s = (scalec) tuning_map.get(tuning_name);
outfile.writeUTF(tuning_name);
for (int i = 0;i < notes_per_octave;i++) {
outfile.writeInt(s.scale[i]);
}
}
prime_list.write_list(outfile);
//for (int i = 0;i < prime_list.num_primes;i++) {
//}
//for (int i = 0;i < pattern_list.size();i++) {
ks = pattern_list.keySet();
for (Iterator it = ks.iterator();it.hasNext();) {
String pat_name = (String) it.next();
patternc p = (patternc) pattern_list.get(pat_name);
outfile.writeShort(p.length);
outfile.writeUTF(p.name);
for (int i = 0;i < ((notes_per_octave>>3)+1);i++) {
outfile.writeByte(p.scale[i]);
}
//if (p.image != null) {
// outfile.writeShort(1);
// outfile.writeUTF(p.image);
//} else {
outfile.writeShort(0);
//}
outfile.writeShort(0);
outfile.writeInt(0);
outfile.writeInt(0);
outfile.writeInt(0);
outfile.writeInt(0);
for (int x = 0;x < p.length;x++) {
//int n = notes_per_octave*num_octaves;
int n = number_of_keys;
for (int y = 0;y <= n;y++) {
outfile.writeByte(p.get_cell(x,y));
}
}
}
for (int i = 0;i < song_list.size();i++) {
song_list_entryc e = (song_list_entryc) main_app.song_list.get(i);
//patternc p = e.pattern;
outfile.writeUTF(e.pattern);
outfile.writeInt(e.cents);
outfile.writeByte(e.mode);
outfile.writeByte(0);
outfile.writeUTF(e.tuning);
}
outfile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//static int get_3fifth() {
// float prime2 = 1000000.0f;
// float prime3 = 1000000.0f;
// for (int i = 0;i < prime_list.num_primes;i++) {
// float p = prime_list.prime_factor[i];
// if (p < prime2) {prime2 = p;}
// else if (p < prime3) {prime3 = p;}
// }
// if (prime_list.num_primes == 1) {prime3 = prime2;}
// int i = (int) (((Math.log(prime3)/Math.log(prime2)) * notes_per_octave) + 0.5);
// return i % notes_per_octave;
//}
static void init_primes_table75() {
//int a = -10 % 10;
//System.out.println("a: " + a);
primes_table75 = new short[60];
int num_primes = 6;
int n = 1;
primes_table75[0] = 2;primes_table75[1] = 3;
primes_table75[2] = 5;primes_table75[3] = 7;
primes_table75[4] = 11;primes_table75[5] = 13;
while (num_primes < 60) {
n = n + 2;
if ((n % 3) == 0) {continue;}
if ((n % 5) == 0) {continue;}
if ((n % 7) == 0) {continue;}
if ((n % 11) == 0) {continue;}
if ((n % 13) == 0) {continue;}
primes_table75[num_primes] = (short) n;
num_primes = num_primes + 1;
}
}
public static void main(String[] args)
throws Exception
{
TextTransfer = new TextTransferc();
init_primes_table75();
//int ptlen = primes_table75.length;
prefs = Preferences.userRoot().node("led_synth23948797523");
int ptlen = prefs.getInt("num_primes",15);
prime_list = new prime_listc(ptlen);
//for (int i = 0;i < ptlen;i++) {
// prime_list.prime_factor[i] = primes_table75[i];
//}
sampleplayerc.sample_rate = prefs.getInt("sample_rate",44100);
sampleplayerc.interpolation = prefs.getInt("interpolation",2);
tuning_map = new HashMap();
pattern_list = new HashMap();
song_list = new Vector();
song_player = new song_playerc(new instrumentc());
get_prefs();
new_song();
pattern_player = new pattern_playerc(song_player);
//pattern_list.add(new patternc(12,"default2"));
javax.swing.SwingUtilities.invokeLater(new main_app());
}
static void get_prefs() {
notes_per_octave = prefs.getInt("notes_per_octave",notes_per_octave);
number_of_keys = prefs.getInt("number_of_keys",number_of_keys);
int b = patternc.black_notes_per_octave;
b = prefs.getInt("black_notes_per_octave",b);
patternc.black_notes_per_octave = b;
scalec.get_prefs(prefs);
}
static void new_song() {
int et = notes_per_octave;
String patname = prefs.get("first_pattern_name","default");
pattern_list.clear();
song_list.clear();
main_panelc.song_pos = -1;
song_player.pattern = new patternc(6,patname);
pattern_list.put(patname,song_player.pattern);
song_list.add(new song_list_entryc(patname,0,0,"t"));
song_player.scale = new scalec(et);
song_player.scale.init();
//for (int i = 0;i < et;i++) {
// song_player.scale.set(i,(int) ((((double)octave_cents)*i)/et));
//}
tuning_map.put("t",song_player.scale);
if (tunning_table_window == null) {
tunning_table_window = new tunning_table_windowc();
}
tunning_table_window.create_new_panel();
if (prime_table_window != null) {
prime_table_window.create_new_panel();
}
main_panelc.filename = null;
main_panelc.dirname = null;
main_panelc.update_low_harmonics();
main_panelc.update_harmonic_offsets();
}
public void run() {
main_frame = new JFrame();
main_panel = new main_panelc();
main_panel_scroller = new JScrollPane(main_panel);
main_frame.getContentPane().setLayout(new BorderLayout());
main_frame.getContentPane().add(main_panel_scroller);
JScrollBar hscroll = main_app.main_panel_scroller.getHorizontalScrollBar();
JScrollBar vscroll = main_app.main_panel_scroller.getVerticalScrollBar();
hscroll.setBlockIncrement(100);
hscroll.setUnitIncrement(30);
vscroll.setBlockIncrement(100);
vscroll.setUnitIncrement(30);
//hscroll = new JScrollBar();
//hscroll.setOrientation(JScrollBar.HORIZONTAL);
//vscroll = new JScrollBar();
//vscroll.setOrientation(JScrollBar.VERTICAL);
harmonic_colors_window = new JFrame();
harmonic_colors_panel = new harmonic_colors_panelc();
harmonic_colors_window.getContentPane().add(harmonic_colors_panel);
harmonic_colors_window.setBounds(20,20,300,300);
hex_keyboard_window = new JFrame();
hex_keyboard_panel = new hex_keyboard_panelc();
hex_keyboard_window.addKeyListener(hex_keyboard_panel);
hex_keyboard_window.getContentPane().add(hex_keyboard_panel);
hex_keyboard_window.setBounds(20,20,300,300);
status_bar = new JLabel("status bar");
main_frame.getContentPane().add(status_bar,BorderLayout.SOUTH);
//main_frame.getContentPane().add(hscroll,BorderLayout.NORTH);
main_frame.addKeyListener(main_panel);
main_panel.addKeyListener(main_panel);
//main_panel_scroller.addKeyListener(main_panel);
main_frame.addWindowListener(main_panel);
main_menu_bar = setup_menu();
main_frame.setJMenuBar(main_menu_bar);
main_frame.setBounds(30,30,500,500);
main_frame.setVisible(true);
main_frame.setTitle("frank's java LED Synthesizer 2.5");
pattern_list_window = new pattern_list_windowc("pattern list");
//pattern_list_window.setVisible(true);
string_table_options_dialog = new string_table_options_dialogc(main_frame,"options");
envelope_dialog = new envelope_dialogc(main_frame,"envelope");
options_dialog = new options_dialogc(main_frame,"options");
new_song_wizard = new new_song_wizardc(main_frame,"new song");
update_status_bar();
pattern_player.start();
main_panel.update_size();
}
JMenuItem createMenuItem(String text,JMenu menu,String action) {
JMenuItem mi = new JMenuItem(text);
menu.add(mi);
mi.setActionCommand(action);
mi.addActionListener(this);
return mi;
}
void load_instrument_as_wave() {
try{
JFileChooser fc = new JFileChooser();
//(hex_keyboard_window,"load instrument",FileDialog.LOAD);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"WAV audio files", "wav");
fc.setFileFilter(filter);
String ins_dir = prefs.get("instrument_directory",null);
if (ins_dir != null) {
fc.setCurrentDirectory(new File(ins_dir));
}
int rv = fc.showOpenDialog(hex_keyboard_window);
if (rv == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
System.out.println(f.getName());
System.out.println(f.getParent());
//String filename = f.getDirectory() + f.getFile();
String dirname = f.getParent() + File.separator;
String filename = dirname + f.getName();
//sampletablec t = new sampletablec(filename);
song_player.ins = new instrumentc(filename);
song_player.update_players();
prefs.put("instrument_directory",dirname);
//prefs.put("instrument_file",f.getName());
}
} catch (Exception err) {
System.out.println("menuopen error");
System.out.println(err.getMessage());
err.printStackTrace();
}
}
JMenuBar setup_menu() {
JMenuBar mb = new JMenuBar();
JMenu file_menu = new JMenu("file");
createMenuItem("new",file_menu,"menu_new");
createMenuItem("open",file_menu,"menu_open");
createMenuItem("save",file_menu,"menu_save");
createMenuItem("export to wave",file_menu,"menu_export_wave");
createMenuItem("options",file_menu,"menu_options");
//createMenuItem("load instrument",file_menu,"menu_open_wave");
createMenuItem("exit",file_menu,"menu_exit");
mb.add(file_menu);
JMenu pattern_menu = new JMenu("pattern");
createMenuItem("new pattern",pattern_menu,"menu_add_pattern");
createMenuItem("double length",pattern_menu,"double_length");
createMenuItem("triple length",pattern_menu,"triple_length");
//createMenuItem("transpose fifth",pattern_menu,"transpose_fifth_up");
//createMenuItem("transpose fourth",pattern_menu,"transpose_fourth_down");
createMenuItem("copy",pattern_menu,"menu_copy");
createMenuItem("paste",pattern_menu,"menu_paste");
createMenuItem("rename",pattern_menu,"menu_rename");
createMenuItem("add random melody",pattern_menu,"add_random_melody");
mb.add(pattern_menu);
JMenu song_menu = new JMenu("song");
//createMenuItem("show equalizer",song_menu,"equalizer");
createMenuItem("parametric equalizer",song_menu,"bass_treble");
createMenuItem("show pattern list",song_menu,"menu_pattern_list");
createMenuItem("get song length",song_menu,"get_song_length");
createMenuItem("show hex keyboard",song_menu,"show_hex_keyboard");
createMenuItem("edit envelope",song_menu,"edit_envelope");
createMenuItem("add random patterns",song_menu,"add_random_patterns");
mb.add(song_menu);
JMenu tunning_table_menu = new JMenu("table");
createMenuItem("view tunning table",tunning_table_menu,"view_tunning_table");
//createMenuItem("generate mean tone",tunning_table_menu,"generate_mean_tone_scale");
createMenuItem("create temperament",tunning_table_menu,"create_temperament");
createMenuItem("import scala",tunning_table_menu,"import_scala");
createMenuItem("export scala",tunning_table_menu,"export_scala");
mb.add(tunning_table_menu);
JMenu harmonics_menu = new JMenu("harmonics");
createMenuItem("edit harmonic colors",harmonics_menu,"edit_harmonic_colors");
createMenuItem("edit prime harmonics",harmonics_menu,"view_prime_table");
createMenuItem("options",harmonics_menu,"str_table_options");
mb.add(harmonics_menu);
return mb;
}
}
| main_app.java | import java.lang.*;
import java.util.*;
import java.io.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.filechooser.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import javax.imageio.*;
import java.awt.image.*;
import java.util.zip.*;
import java.util.prefs.Preferences;
public class main_app implements Runnable,ActionListener {
static JFrame main_frame;
static pattern_list_windowc pattern_list_window;
static main_panelc main_panel;
static harmonic_colors_panelc harmonic_colors_panel;
static JFrame harmonic_colors_window;
static hex_keyboard_panelc hex_keyboard_panel;
//static equalizer_windowc equalizer_window;
static bass_treble_windowc bass_treble_window;
static JFrame hex_keyboard_window;
static JMenuBar main_menu_bar;
static song_playerc song_player;
static int sqsize = 32;
static int notes_per_octave = 12;
static int number_of_keys = 120;
//static int num_octaves = 10;
//static int octave_cents = 1200;
static float tempo = 60.0f;
//static int scale[];
//static int octave_offset = 0;
static int base_freq = 16;
static int wolf_fifth_cents = 0;
static pattern_playerc pattern_player;
static int ID_NUM = 244368531;
static int pan_note = 2;
static JLabel status_bar;
static boolean song_modified = false;
static HashMap pattern_list;
static HashMap tuning_map;
static Vector song_list;
static int PATTERN_MODE = 0;
static int SONG_MODE = 1;
static int NOTE_MODE = 2;
static int play_mode = SONG_MODE;
static options_dialogc options_dialog;
//static new_song_dialogc new_song_dialog;
static new_song_wizardc new_song_wizard;
static JScrollPane main_panel_scroller;
static wave_writerc wave_writer;
static tunning_table_windowc tunning_table_window;
static string_table_options_dialogc string_table_options_dialog;
static TextTransferc TextTransfer;
static Preferences prefs;
static export_wave_dialogc export_wave_dialog;
static envelope_dialogc envelope_dialog;
static short primes_table75[];
//static short primes_table75[] = {2};
//static short primes_table75[] =
//{2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97};
static prime_listc prime_list; //= new prime_listc(9);
static prime_table_windowc prime_table_window = null;
//static int harmonic_pos[] = new int[4];
static create_temperament_dialog CT_dialog;
static double get_centsf(float f) {
return (((Math.log(f) / Math.log(2)) * 1200)+0.5);
}
static int get_num_steps_from_cents(int c) {
double f1 = c;
f1 = f1 * main_app.notes_per_octave;
double f2 = song_player.scale.interval_size;
double f3 = f1/f2;
if (f3 < 0) {
return (int) (f3-0.5);
}
return (int) (f3+0.5);
}
void display_song_length() {
int total_length = 0;
for (int i = 0;i < song_list.size();i++) {
song_list_entryc e = (song_list_entryc) song_list.get(i);
patternc pat = (patternc) pattern_list.get(e.pattern);
total_length = total_length + pat.length;
}
float f = total_length;
f = (f / tempo) * 60.0f;
int minutes = (int) (f / 60);
int seconds = (((int) f ) % 60);
JOptionPane.showMessageDialog(main_frame,"this song is " + minutes + " minutes and " + seconds + " seconds long","info",JOptionPane.INFORMATION_MESSAGE);
}
void add_random_patterns() {
String msg = "how many patterns to add?";
String number_string = JOptionPane.showInputDialog(main_frame,msg,"10");
if (number_string == null) {return;}
Random rand = new Random();
try {
int n = Integer.parseInt(number_string);
Set s = pattern_list.keySet();
Object pnames[] = s.toArray();
int psize = s.size();
s = tuning_map.keySet();
Object tnames[] = s.toArray();
int tsize = s.size();
int os = song_player.scale.interval_size;
for (int i = 0;i < n;i++) {
String pname = (String) pnames[rand.nextInt(psize)];
String tname = (String) tnames[rand.nextInt(tsize)];
int m = rand.nextInt(notes_per_octave);
m = m - (notes_per_octave >> 1);
int c = (-m * os) / notes_per_octave;
c = c + rand.nextInt(os) - (os >> 1);
double k = scalec.cents_to_key(c);
k = Math.rint(k);
c = scalec.key_to_cents(k);
//k = k + rand.nextInt(1200)-600;
//int ed = scalec.equal_divisions;
//int d = rand.nextInt(ed) - (ed >> 1);
//d = d - (notes_per_octave >> 1);
//k = k + scalec.key_to_cents(d);
song_list.add(new song_list_entryc(pname,m,c,tname));
}
} catch (java.lang.NumberFormatException e) {
JOptionPane.showMessageDialog(main_frame,
"invalid number","error",
JOptionPane.ERROR_MESSAGE);
}
pattern_list_window.update_list_box();
//pattern_list_window.update_list_box();
}
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
patternc pattern = song_player.pattern;
if (action.equals("menu_new")) {
if (main_app.song_modified == true) {
main_app.save_song_prompt();
}
//new_song_dialog.show();
new_song_wizard.show();
}
if (action.equals("edit_harmonic_colors")) {
harmonic_colors_window.show();
}
if (action.equals("menu_open_wave")) {
load_instrument_as_wave();
}
if (action.equals("menu_open")) {
open2();
}
if (action.equals("menu_save")) {
save2();
}
if (action.equals("menu_export_wave")) {
export_wave();
}
if (action.equals("menu_options")) {
options_dialog.show();
}
if (action.equals("menu_exit")) {
exit2();
}
if (action.equals("str_table_options")) {
string_table_options_dialog.show();
}
if (action.equals("menu_add_pattern")) {
patternc p = pattern_list_model.create_new_pattern(main_frame);
if (p != null) {
pattern_list_window.add_to_song_list(p.name);
}
}
if (action.equals("double_length")) {
pattern.double_length();
main_panel.repaint();
main_app.update_status_bar();
}
if (action.equals("triple_length")) {
pattern.triple_length();
main_panel.repaint();
main_app.update_status_bar();
}
if (action.equals("transpose_fifth_up")) {
JOptionPane.showMessageDialog(main_frame,
"transpose_fifth_up is obsolete",
"error",
JOptionPane.ERROR_MESSAGE);
//pattern.transpose_fifth_up();
main_panel.repaint();
}
if (action.equals("transpose_fourth_down")) {
JOptionPane.showMessageDialog(main_frame,
"transpose_fourth_down is obsolete",
"error",
JOptionPane.ERROR_MESSAGE);
//pattern.transpose_fourth_down();
main_panel.repaint();
}
if (action.equals("menu_pattern_list")) {
pattern_list_window.show();
}
if (action.equals("menu_copy")) {
String str = pattern.write_to_string();
TextTransfer.setClipboardContents(str);
}
if (action.equals("menu_paste")) {
String str = TextTransfer.getClipboardContents();
patternc p = patternc.read_pattern_from_string(str);
if (p != null) {
pattern_list_model.add_pattern(p);
pattern_list_window.add_to_song_list(p.name);
pattern = p;
}
}
//if (action.equals("add_random_patterns")) {
// add_random_patterns();
//}
if (action.equals("menu_rename")) {
String msg = "enter a new name for the pattern";
String new_string = JOptionPane.showInputDialog(main_frame,msg,pattern.name);
if (new_string != null) {
pattern_list_window.update_pattern_name(new_string);
pattern.name = new_string;
}
}
if (action.equals("edit_envelope")) {
envelope_dialog.show();
}
if (action.equals("bass_treble")) {
if (bass_treble_window == null) {
bass_treble_window = new bass_treble_windowc();
}
bass_treble_window.show();
}
//if (action.equals("equalizer")) {
// if (equalizer_window == null) {
// equalizer_window = new equalizer_windowc();
// }
// equalizer_window.show();
//}
if (action.equals("show_hex_keyboard")) {
hex_keyboard_window.show();
}
if (action.equals("get_song_length")) {
display_song_length();
}
if (action.equals("add_random_patterns")) {
add_random_patterns();
}
if (action.equals("view_prime_table")) {
if (prime_table_window == null) {
prime_table_window = new prime_table_windowc();
}
prime_table_window.show();
}
if (action.equals("view_tunning_table")) {
tunning_table_window.show();
}
if (action.equals("create_temperament")) {
create_temperament_dialog d = new create_temperament_dialog(main_frame,"create temperament");
d.show();
if (d.OK_Clicked()) {
//double cents = d.get_offset();
//double generator = d.get_generator_cents();
//int octave_cents = main_app.octave_cents;
//double ed = scalec.equal_divisions;
//Double s[] = new Double[notes_per_octave];
//for (int i = 0;i < notes_per_octave;i++) {
// s[i] = new Double( cents);
// cents = cents + generator;
// if (cents > ed) {cents = cents - ed;}
//}
//Arrays.sort(s);
//for (int i = 0;i < notes_per_octave;i++) {
// tunning_table_window.spinner[i].setValue(s[i]);
//}
song_player.scale.init();
tunning_table_window.update();
//System.out.println("OK_Clicked");
}
}
if (action.equals("generate_mean_tone_scale")) {
JOptionPane.showMessageDialog(main_frame,
"generate_mean_tone_scale is obsolete",
"error",
JOptionPane.ERROR_MESSAGE);
}
/*
if (action.equals("generate_mean_tone_scale")) {
generate_mean_tone_scale_dialog d = new generate_mean_tone_scale_dialog(main_frame,"generate mean tone scale");
d.show();
if (d.OK_Clicked()) {
//int octave_cents = main_app.octave_cents;
int start = d.get_start_note();
int step = d.get_step_value();
double interval = d.get_interval();
byte a[] = new byte[notes_per_octave];
int i = start;
double cents = song_player.scale.get(start);
while (a[i] != 32) {
a[i] = 32;
tunning_table_window.spinner[i].setValue(new Integer((int) cents));
cents = cents + interval;
if (cents > octave_cents) {cents = cents - octave_cents;}
i = (i + step) % notes_per_octave;
}
}
}
*/
if (action.equals("import_scala")) {
import_scala();
}
if (action.equals("export_scala")) {
export_scala();
}
}
static void import_scala() {
try{
FileDialog f = new FileDialog(main_frame,"import scala",FileDialog.LOAD);
f.show();
if (f.getFile() != null) {
String filename = f.getDirectory() + f.getFile();
scl_file sf = new scl_file();
sf.read_table(filename,song_player.scale);
tunning_table_window.update();
}
} catch (Exception err) {
System.out.println("menusave error");
System.out.println(err.getMessage());
err.printStackTrace();
}
}
static void export_scala() {
try{
FileDialog f = new FileDialog(main_frame,"export scala",FileDialog.SAVE);
f.show();
if (f.getFile() != null) {
String title = JOptionPane.showInputDialog("Enter a title for this scale");
if (title != null) {
File f2 = new File(f.getDirectory() + f.getFile());
if (f2.exists() == false) {
scl_file sf = new scl_file();
sf.write_table(f.getDirectory(),f.getFile(),title,song_player.scale);
tunning_table_window.update();
} else {
JOptionPane.showMessageDialog(main_frame,new JLabel("file already exists"),"error",JOptionPane.ERROR_MESSAGE);
}
}
}
} catch (Exception err) {
System.out.println("menusave error");
System.out.println(err.getMessage());
err.printStackTrace();
}
}
static void export_wave() {
try{
//FileDialog f = new FileDialog(main_frame,"export to wave",FileDialog.SAVE);
//System.out.println("tmp: " + System.getProperty("java.io.tmpdir"));
//String tmp_dir = System.getProperty("java.io.tmpdir");
//String tmp_dir = "";
String tmp_dir = prefs.get("export_wave_directory",main_panelc.dirname);
JFileChooser fc = new JFileChooser();
fc.setSelectedFile(new File(tmp_dir,"output90613708930439146539.wav"));
int r = fc.showDialog(main_frame,"export to wave");
//f.setDirectory(main_panelc.dirname);
//f.setFile("output90613708930439146539.wav");
//f.show();
if (r == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
//String filename = f.getDirectory() + f.getFile();
String filename = f.getParent() + File.separator + f.getName();
prefs.put("export_wave_directory",f.getParent());
System.out.println(filename);
//pattern_list_window.table.changeSelection(0,0,false,false);
boolean b = wave_writerc.read_wave_id(new File(filename));
if (b == true) {
if (export_wave_dialog == null) {
export_wave_dialog = new export_wave_dialogc(main_frame);
}
export_wave_dialogc d = export_wave_dialog;
d.setVisible(true);
if (d.ok_clicked) {
Number n = null;
n = (Number) d.fade_in_spinner.getValue();
float fi = n.floatValue();
n = (Number) d.fade_out_spinner.getValue();
float fo = n.floatValue();
boolean st = d.op_stereo.isSelected();
boolean sh = d.op_16bit.isSelected();
prefs.putBoolean("wave_stereo",st);
prefs.putBoolean("wave_16bit",sh);
prefs.putDouble("wave_fade_in",fi);
prefs.putDouble("wave_fade_out",fo);
main_app.wave_writer = new wave_writerc(filename,st,sh,fi,fo);
main_app.wave_writer.write_song();
main_app.wave_writer.close();
}
} else {
JOptionPane.showMessageDialog(main_frame,"error: file already exists","error",JOptionPane.ERROR_MESSAGE);
}
}
} catch (Exception err) {
System.out.println("menusave error");
System.out.println(err.getMessage());
err.printStackTrace();
}
}
static int save_song_prompt() {
int op = JOptionPane.showConfirmDialog(main_frame,
"Do you want to save your song?","save song?",
JOptionPane.YES_NO_OPTION);
if (op == JOptionPane.YES_OPTION) {
save2();
}
return op;
}
static void exit2() {
try{
while (main_app.song_modified == true) {
int old_vol = pattern_player.volume;
pattern_player.volume = 0;
int op = save_song_prompt();
if (op == JOptionPane.NO_OPTION) {
System.exit(0);
}
}
System.exit(0);
} catch(SecurityException err){
System.out.println("can not exit");
}
}
static void update_status_bar() {
String str = "volume: " + pattern_player.volume;
//str = str + " bass: " + pattern_player.bass;
//int o = num_octaves-octave_offset;
str = str + " pan: ";
if (pan_note == 1) {str = str + "left";}
if (pan_note == 2) {str = str + "center";}
if (pan_note == 3) {str = str + "right";}
if (play_mode == PATTERN_MODE) {str = str + " mode: P ";}
if (play_mode == SONG_MODE) {str = str + " mode: S ";}
if (play_mode == NOTE_MODE) {str = str + " mode: N ";}
str = str + " length: " + song_player.pattern.get_length();
int sh = main_panelc.sel_harmonic;
int h = (int)((main_panelc.harmonic_low[sh]*10)+0.5);
str = str + " harmonic: ";
str = str + ((int) (h/10)) + ".";
str = str + ((int) (h%10));
status_bar.setText(str);
}
static void open2() {
try{
FileDialog f = new FileDialog(main_frame,"open pattern",FileDialog.LOAD);
main_panelc.dirname = prefs.get("song_directory",main_panelc.dirname);
//System.out.println(main_panelc.dirname);
f.setDirectory(main_panelc.dirname);
//f.setDirectory("a3928798237");
f.show();
if (f.getFile() != null) {
String filename = f.getDirectory() + f.getFile();
int ft = get_file_type(filename);
if (ft == 1) {
DataInputStream infile = new DataInputStream(new BufferedInputStream(
new GZIPInputStream(new FileInputStream(filename))));
open_file(infile);
} else if (ft == 2) {
new song_browserc(filename);
} else {
JOptionPane.showMessageDialog(main_frame,
"error: invalid gz file","can not open file",
JOptionPane.ERROR_MESSAGE);
}
main_panel.repaint();
main_panelc.filename = f.getFile();
main_panelc.dirname = f.getDirectory();
prefs.put("song_directory",main_panelc.dirname);
}
} catch (Exception err) {
System.out.println("menuopen error");
System.out.println(err.getMessage());
err.printStackTrace();
}
}
static void save2() {
try{
FileDialog f = new FileDialog(main_frame,"save pattern",FileDialog.SAVE);
main_panelc.dirname = prefs.get("song_directory",null);
f.setDirectory(main_panelc.dirname);
//f.setFile(main_panelc.filename);
f.show();
if (f.getFile() != null) {
String filename = f.getDirectory() + f.getFile();
File f2 = new File(filename);
String filename2 = main_panelc.dirname;
filename2 = filename2 + main_panelc.filename;
if ((f2.exists() == false) | (filename.equals(filename2)) == true) {
save_file(filename);
main_panelc.filename = f.getFile();
main_panelc.dirname = f.getDirectory();
prefs.put("song_directory",main_panelc.dirname);
} else {
JOptionPane.showMessageDialog(main_frame,new JLabel("file already exists"),"error",JOptionPane.ERROR_MESSAGE);
}
}
} catch (Exception err) {
System.out.println("menusave error");
System.out.println(err.getMessage());
err.printStackTrace();
}
}
static int get_file_type(String filename) {
try {
byte b[] = new byte[4];
InputStream in = new FileInputStream(filename);
in.read(b);
//System.out.println("bytes: " + b[0] + " " + b[1] + " " + b[2] + " " + b[3]);
if ((b[0] == 31) & (b[1] == -117) & (b[2] == 8) & (b[3] == 0)) {
return 1;
}
if ((b[0] == 0x50) & (b[1] == 0x4b) & (b[2] == 0x03) & (b[3] == 0x04)) {
return 2;
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
static boolean isColorDark(int col) {
int a = (col&255)+((col>>8)&255)+((col>>16)&255);
if (a < 384) {return true;}
return false;
}
static Color get_text_color(Color col) {
return get_text_color(color_to_int(col));
}
static Color get_text_color(int col) {
if (isColorDark(col) == true) {
return Color.white;
} else {
return Color.black;
}
}
static int color_to_int(Color col) {
int red = col.getRed();
int green = col.getGreen();
int blue = col.getBlue();
return red + (green << 8) + (blue << 16);
}
static Color int_to_color(int col) {
int red = col & 255;
int green = (col >> 8) & 255;
int blue = (col >> 16) & 255;
return new Color(red,green,blue);
}
static void open_file(DataInputStream infile) {
try {
int id = infile.readInt();
if (id != ID_NUM) {
JOptionPane.showMessageDialog(main_frame,
"error: invalid gz file",
"can not open file",
JOptionPane.ERROR_MESSAGE);
return;
}
int version = infile.readUnsignedShort();
if ((version < 0) | (version >= 9)) {
JOptionPane.showMessageDialog(main_frame,
"error: the file is too new",
"can not open file",
JOptionPane.ERROR_MESSAGE);
return;
}
main_panelc.song_pos = -1;
notes_per_octave = infile.readUnsignedByte();
if ((notes_per_octave == 0) & (version >= 8)) {
notes_per_octave = 256;
}
scalec.equal_divisions = (short) notes_per_octave;
scalec.period = (short) notes_per_octave;
//scale = new int[notes_per_octave];
scalec scale = new scalec(notes_per_octave);
song_player.scale = scale;
if (version >= 8) {
number_of_keys = infile.readInt();
} else {
int num_octaves = infile.readUnsignedByte();
number_of_keys = num_octaves*notes_per_octave;
}
int num_patterns = 0;
if (version >= 1) {num_patterns = infile.readInt();}
else {num_patterns = infile.readUnsignedByte()+1;}
int num_primes = infile.readUnsignedByte();
prime_list = new prime_listc(num_primes);
base_freq = infile.readUnsignedShort();
int song_length = infile.readInt();
int num_extra_bytes = 0;
Vector pattern_name_list = new Vector();
if (version >= 7) {
song_playerc.highest_note_freq = infile.readInt();
if (version >= 8) {
infile.readInt();
} else {
int sample_rate = infile.readInt();
if (pattern_playerc.sample_rate != sample_rate) {
equalizer.sample_rate_changed();
pattern_playerc.sample_rate = sample_rate;
}
}
equalizer e2 = equalizer.e2;
e2.read(infile,version);
equalizer.e1.copy(e2);
equalizer.e3.copy(e2);
infile.readShort();
if (version >= 8) {
infile.readByte();
} else {
sampleplayerc.interpolation = infile.readByte();
}
if (bass_treble_window != null) {
bass_treble_window.update();
}
}
if (version >= 4) {
infile.readByte();
if (version >= 6) {
infile.readInt();
infile.readInt();
}
num_extra_bytes = infile.readInt();
//System.out.println(num_extra_bytes);
if (version <= 7) {
scalec.interval_size = infile.readShort() << 16;
}
tempo = infile.readFloat();
main_panelc.harmonic_color.clear();
int nh = infile.readInt();
for (int i = 0;i < nh;i++) {
main_panelc.harmonic_color.add(int_to_color(infile.readInt()));
}
//System.out.println("num_extra_bytes: " + num_extra_bytes);
if (num_extra_bytes >= 10) {
num_extra_bytes = num_extra_bytes - 10;
int b = infile.readByte();
pattern_player.ins.string_table_num_octaves = b;
//System.out.println("num_octaves: " + b);
b = infile.readByte();
if (version <= 7) {b = b+b+20;}
int minSize = string_table_options_dialogc.minSize;
int maxSize = string_table_options_dialogc.maxSize;
if (b < minSize) {b = minSize;}
if (b > maxSize) {b = maxSize;}
pattern_player.ins.string_table_psize = b;
//System.out.println("table_psize: " + b);
int s = infile.readInt();
pattern_player.ins.string_table_seed = s;
//System.out.println("seed: " + s);
float bandwidth = infile.readFloat();
pattern_player.ins.bandwidth = bandwidth;
//System.out.println("bandwidth: " + bandwidth);
if (num_extra_bytes >= 4) {
num_extra_bytes = num_extra_bytes - 4;
hex_keyboard_panelc.x_step = infile.readShort();
hex_keyboard_panelc.y_step = infile.readShort();
if (num_extra_bytes >= 16) {
num_extra_bytes = num_extra_bytes - 16;
sampleplayerc.envelope.read(infile);
}
}
}
}
//num_extra_bytes = num_extra_bytes + 2;
//System.out.println(num_extra_bytes);
for (int i = 0;i < num_extra_bytes;i++) {
infile.readUnsignedByte();
}
if (version >= 8) {
scalec.interval_size = infile.readInt();
//System.out.println("interval_size: " + scalec.interval_size);
scalec.equal_divisions = infile.readUnsignedShort();
//System.out.println("equal_divisions: " + scalec.equal_divisions);
scalec.generator = infile.readFloat();
//System.out.println("generator: " + scalec.generator);
scalec.period = infile.readFloat();
//System.out.println("period: " + scalec.period);
}
if (version == 3) {
infile.readByte();
int header_size = 32;
int header_size2 = infile.readInt();
num_extra_bytes = header_size2-header_size;
scalec.interval_size = infile.readShort() << 16;
tempo = infile.readFloat();
}
if (version < 3) {
if (version >= 1) {
infile.readInt();infile.readInt();
infile.readInt();infile.readInt();
}
infile.readInt();infile.readInt();
infile.readInt();infile.readShort();
}
song_list.clear();
pattern_list.clear();
tuning_map.clear();
//System.out.println("tunings ");
if (version >= 3) {
if (version >= 6) {
int num_tunings = infile.readInt();
for (int i = 0;i < num_tunings;i++) {
scale = new scalec(notes_per_octave);
String tuning_name = infile.readUTF();
//System.out.println("tuning: " + tuning_name);
if (version >= 8) {
for (int j = 0;j < notes_per_octave;j++) {
scale.scale[j] = infile.readInt();
}
} else {
for (int j = 0;j < notes_per_octave;j++) {
scale.scale[j] = infile.readShort() << 16;
}
}
tuning_map.put(tuning_name,scale);
}
} else {
for (int i = 0;i < notes_per_octave;i++) {
scale.scale[i] = infile.readShort() << 16;
}
tuning_map.put("t",scale);
}
}
if (version >= 8) {
prime_list.read_list(infile);
} else {
for (int i = 0;i < prime_list.num_primes;i++) {
prime_list.prime_factor[i] = infile.readFloat();
}
}
for (int i = 0;i < num_patterns;i++) {
int length = infile.readUnsignedShort();
//System.out.println("length: " + length);
patternc pattern = new patternc(length);
song_player.pattern = pattern;
if (version >= 1) {
pattern.name = infile.readUTF();
if (version >= 6) {
for (int j = 0;j < ((notes_per_octave>>3)+1);j++) {
pattern.scale[j] = infile.readByte();
}
}
int b = infile.readShort();
if ((b & 1) == 1) {
pattern.image = infile.readUTF();
}
infile.readShort();
infile.readInt();
infile.readInt();
infile.readInt();
infile.readInt();
} else {
pattern.name = "pattern";
}
for (int x = 0;x < pattern.length;x++) {
int n = number_of_keys;
if (version == 0) {n = n - 1;}
for (int y = 0;y <= n;y++) {
int a = infile.readByte();
pattern.set_cell(x,y,a);
}
}
String patternname2 = pattern.name;
int x = 2;
while (pattern_list.get(patternname2) != null) {
patternname2 = pattern.name + x;
x = x + 1;
}
pattern_list.put(patternname2,pattern);
if (version <= 4) {
pattern_name_list.add(patternname2);
}
}
//pattern_player.volume = 1;
for (int i = 0;i < song_length;i++) {
String pat_name;
if (version >= 5) {
pat_name = infile.readUTF();
} else {
int i2 = infile.readInt();
pat_name = (String) pattern_name_list.get(i2);
}
patternc p = (patternc) main_app.pattern_list.get(pat_name);
song_list_entryc en = new song_list_entryc(pat_name,0,0,"t");
main_app.song_list.add(en);
if (version >= 2) {
if (version >= 8) {
en.cents = infile.readInt();
} else {
en.cents = infile.readShort() << 16;
}
en.mode = infile.readByte();
infile.readByte();
}
if (version >= 6) {
en.tuning = infile.readUTF();
}
}
//pattern_list_model.update_pattern_list_ids();
pattern_list_window.update_list_box();
main_app.song_modified = false;
main_app.main_panel.update_size();
main_app.song_player.create_players();
//main_panelc.setup_scale34(main_app.notes_per_octave);
tunning_table_window.create_new_panel();
if (prime_table_window != null) {
prime_table_window.create_new_panel();
}
main_panelc.update_harmonics();
//main_panelc.update_harmonic_offsets();
//main_app.pattern_player.alloc_string_tables(6);
//main_app.pattern_player.update_players();
//if (main_app.song_list.size() > 0) {
// pattern_list_window.table.setSelectedRow(0);
//}
main_app.pattern_list_window.play_next_pattern();
infile.close();
update_status_bar();
} catch (Exception e) {
e.printStackTrace();
}
}
static void save_file(String filename) {
try {
main_app.song_modified = false;
DataOutputStream outfile = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(filename))));
outfile.writeInt(ID_NUM); //ID
outfile.writeShort(8); //Version
outfile.writeByte(notes_per_octave);
//int bn = patternc.black_notes_per_octave;
//outfile.writeByte(bn);
//outfile.writeByte(num_octaves);
outfile.writeInt(number_of_keys);
outfile.writeInt(pattern_list.size());//num patterns
outfile.writeByte(prime_list.num_primes);
outfile.writeShort(base_freq);
outfile.writeInt(song_list.size());//song length
outfile.writeInt(song_playerc.highest_note_freq);
outfile.writeInt(0);
equalizer.e2.write(outfile);
outfile.writeShort(0);
outfile.writeByte(0);
outfile.writeByte(0);
outfile.writeInt(0);
outfile.writeInt(0);
outfile.writeInt(30);//extra bytes
outfile.writeFloat(tempo);
outfile.writeInt(main_panelc.harmonic_color.size());
for (int i = 0;i < main_panelc.harmonic_color.size();i++) {
Color c = (Color) main_panelc.harmonic_color.get(i);
outfile.writeInt(color_to_int(c));
}
int b = 0;
b = pattern_player.ins.string_table_num_octaves;
outfile.writeByte(b);
b = pattern_player.ins.string_table_psize;
outfile.writeByte(b);
int seed = pattern_player.ins.string_table_seed;
outfile.writeInt(seed);
float bandwidth = pattern_player.ins.bandwidth;
outfile.writeFloat(bandwidth);
int x_step = hex_keyboard_panelc.x_step;
outfile.writeShort(x_step);
int y_step = hex_keyboard_panelc.y_step;
outfile.writeShort(y_step);
sampleplayerc.envelope.write(outfile);
outfile.writeInt(scalec.interval_size);
outfile.writeShort(scalec.equal_divisions);
outfile.writeFloat((float) scalec.generator);
outfile.writeFloat((float) scalec.period);
//for (int i = 0;i < notes_per_octave;i++) {
// outfile.writeShort(scale.get(i));
//}
outfile.writeInt(tuning_map.size());
Set ks = tuning_map.keySet();
for (Iterator it = ks.iterator();it.hasNext();) {
String tuning_name = (String) it.next();
scalec s = (scalec) tuning_map.get(tuning_name);
outfile.writeUTF(tuning_name);
for (int i = 0;i < notes_per_octave;i++) {
outfile.writeInt(s.scale[i]);
}
}
prime_list.write_list(outfile);
//for (int i = 0;i < prime_list.num_primes;i++) {
//}
//for (int i = 0;i < pattern_list.size();i++) {
ks = pattern_list.keySet();
for (Iterator it = ks.iterator();it.hasNext();) {
String pat_name = (String) it.next();
patternc p = (patternc) pattern_list.get(pat_name);
outfile.writeShort(p.length);
outfile.writeUTF(p.name);
for (int i = 0;i < ((notes_per_octave>>3)+1);i++) {
outfile.writeByte(p.scale[i]);
}
//if (p.image != null) {
// outfile.writeShort(1);
// outfile.writeUTF(p.image);
//} else {
outfile.writeShort(0);
//}
outfile.writeShort(0);
outfile.writeInt(0);
outfile.writeInt(0);
outfile.writeInt(0);
outfile.writeInt(0);
for (int x = 0;x < p.length;x++) {
//int n = notes_per_octave*num_octaves;
int n = number_of_keys;
for (int y = 0;y <= n;y++) {
outfile.writeByte(p.get_cell(x,y));
}
}
}
for (int i = 0;i < song_list.size();i++) {
song_list_entryc e = (song_list_entryc) main_app.song_list.get(i);
//patternc p = e.pattern;
outfile.writeUTF(e.pattern);
outfile.writeInt(e.cents);
outfile.writeByte(e.mode);
outfile.writeByte(0);
outfile.writeUTF(e.tuning);
}
outfile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//static int get_3fifth() {
// float prime2 = 1000000.0f;
// float prime3 = 1000000.0f;
// for (int i = 0;i < prime_list.num_primes;i++) {
// float p = prime_list.prime_factor[i];
// if (p < prime2) {prime2 = p;}
// else if (p < prime3) {prime3 = p;}
// }
// if (prime_list.num_primes == 1) {prime3 = prime2;}
// int i = (int) (((Math.log(prime3)/Math.log(prime2)) * notes_per_octave) + 0.5);
// return i % notes_per_octave;
//}
static void init_primes_table75() {
//int a = -10 % 10;
//System.out.println("a: " + a);
primes_table75 = new short[60];
int num_primes = 6;
int n = 1;
primes_table75[0] = 2;primes_table75[1] = 3;
primes_table75[2] = 5;primes_table75[3] = 7;
primes_table75[4] = 11;primes_table75[5] = 13;
while (num_primes < 60) {
n = n + 2;
if ((n % 3) == 0) {continue;}
if ((n % 5) == 0) {continue;}
if ((n % 7) == 0) {continue;}
if ((n % 11) == 0) {continue;}
if ((n % 13) == 0) {continue;}
primes_table75[num_primes] = (short) n;
num_primes = num_primes + 1;
}
}
public static void main(String[] args)
throws Exception
{
TextTransfer = new TextTransferc();
init_primes_table75();
//int ptlen = primes_table75.length;
prefs = Preferences.userRoot().node("led_synth23948797523");
int ptlen = prefs.getInt("num_primes",15);
prime_list = new prime_listc(ptlen);
//for (int i = 0;i < ptlen;i++) {
// prime_list.prime_factor[i] = primes_table75[i];
//}
sampleplayerc.sample_rate = prefs.getInt("sample_rate",44100);
sampleplayerc.interpolation = prefs.getInt("interpolation",2);
tuning_map = new HashMap();
pattern_list = new HashMap();
song_list = new Vector();
song_player = new song_playerc(new instrumentc());
get_prefs();
new_song();
pattern_player = new pattern_playerc(song_player);
//pattern_list.add(new patternc(12,"default2"));
javax.swing.SwingUtilities.invokeLater(new main_app());
}
static void get_prefs() {
notes_per_octave = prefs.getInt("notes_per_octave",notes_per_octave);
number_of_keys = prefs.getInt("number_of_keys",number_of_keys);
int b = patternc.black_notes_per_octave;
b = prefs.getInt("black_notes_per_octave",b);
patternc.black_notes_per_octave = b;
scalec.get_prefs(prefs);
}
static void new_song() {
int et = notes_per_octave;
String patname = prefs.get("first_pattern_name","default");
pattern_list.clear();
song_list.clear();
main_panelc.song_pos = -1;
song_player.pattern = new patternc(6,patname);
pattern_list.put(patname,song_player.pattern);
song_list.add(new song_list_entryc(patname,0,0,"t"));
song_player.scale = new scalec(et);
song_player.scale.init();
//for (int i = 0;i < et;i++) {
// song_player.scale.set(i,(int) ((((double)octave_cents)*i)/et));
//}
tuning_map.put("t",song_player.scale);
if (tunning_table_window == null) {
tunning_table_window = new tunning_table_windowc();
}
tunning_table_window.create_new_panel();
if (prime_table_window != null) {
prime_table_window.create_new_panel();
}
main_panelc.filename = null;
main_panelc.dirname = null;
main_panelc.update_low_harmonics();
main_panelc.update_harmonic_offsets();
}
public void run() {
main_frame = new JFrame();
main_panel = new main_panelc();
main_panel_scroller = new JScrollPane(main_panel);
main_frame.getContentPane().setLayout(new BorderLayout());
main_frame.getContentPane().add(main_panel_scroller);
JScrollBar hscroll = main_app.main_panel_scroller.getHorizontalScrollBar();
JScrollBar vscroll = main_app.main_panel_scroller.getVerticalScrollBar();
hscroll.setBlockIncrement(100);
hscroll.setUnitIncrement(30);
vscroll.setBlockIncrement(100);
vscroll.setUnitIncrement(30);
//hscroll = new JScrollBar();
//hscroll.setOrientation(JScrollBar.HORIZONTAL);
//vscroll = new JScrollBar();
//vscroll.setOrientation(JScrollBar.VERTICAL);
harmonic_colors_window = new JFrame();
harmonic_colors_panel = new harmonic_colors_panelc();
harmonic_colors_window.getContentPane().add(harmonic_colors_panel);
harmonic_colors_window.setBounds(20,20,300,300);
hex_keyboard_window = new JFrame();
hex_keyboard_panel = new hex_keyboard_panelc();
hex_keyboard_window.addKeyListener(hex_keyboard_panel);
hex_keyboard_window.getContentPane().add(hex_keyboard_panel);
hex_keyboard_window.setBounds(20,20,300,300);
status_bar = new JLabel("status bar");
main_frame.getContentPane().add(status_bar,BorderLayout.SOUTH);
//main_frame.getContentPane().add(hscroll,BorderLayout.NORTH);
main_frame.addKeyListener(main_panel);
main_panel.addKeyListener(main_panel);
//main_panel_scroller.addKeyListener(main_panel);
main_frame.addWindowListener(main_panel);
main_menu_bar = setup_menu();
main_frame.setJMenuBar(main_menu_bar);
main_frame.setBounds(30,30,500,500);
main_frame.setVisible(true);
main_frame.setTitle("frank's java LED Synthesizer 2.5");
pattern_list_window = new pattern_list_windowc("pattern list");
//pattern_list_window.setVisible(true);
string_table_options_dialog = new string_table_options_dialogc(main_frame,"options");
envelope_dialog = new envelope_dialogc(main_frame,"envelope");
options_dialog = new options_dialogc(main_frame,"options");
new_song_wizard = new new_song_wizardc(main_frame,"new song");
update_status_bar();
pattern_player.start();
main_panel.update_size();
}
JMenuItem createMenuItem(String text,JMenu menu,String action) {
JMenuItem mi = new JMenuItem(text);
menu.add(mi);
mi.setActionCommand(action);
mi.addActionListener(this);
return mi;
}
void load_instrument_as_wave() {
try{
JFileChooser fc = new JFileChooser();
//(hex_keyboard_window,"load instrument",FileDialog.LOAD);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"WAV audio files", "wav");
fc.setFileFilter(filter);
String ins_dir = prefs.get("instrument_directory",null);
if (ins_dir != null) {
fc.setCurrentDirectory(new File(ins_dir));
}
int rv = fc.showOpenDialog(hex_keyboard_window);
if (rv == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
System.out.println(f.getName());
System.out.println(f.getParent());
//String filename = f.getDirectory() + f.getFile();
String dirname = f.getParent() + File.separator;
String filename = dirname + f.getName();
//sampletablec t = new sampletablec(filename);
song_player.ins = new instrumentc(filename);
song_player.update_players();
prefs.put("instrument_directory",dirname);
//prefs.put("instrument_file",f.getName());
}
} catch (Exception err) {
System.out.println("menuopen error");
System.out.println(err.getMessage());
err.printStackTrace();
}
}
JMenuBar setup_menu() {
JMenuBar mb = new JMenuBar();
JMenu file_menu = new JMenu("file");
createMenuItem("new",file_menu,"menu_new");
createMenuItem("open",file_menu,"menu_open");
createMenuItem("save",file_menu,"menu_save");
createMenuItem("export to wave",file_menu,"menu_export_wave");
createMenuItem("options",file_menu,"menu_options");
//createMenuItem("load instrument",file_menu,"menu_open_wave");
createMenuItem("exit",file_menu,"menu_exit");
mb.add(file_menu);
JMenu pattern_menu = new JMenu("pattern");
createMenuItem("new pattern",pattern_menu,"menu_add_pattern");
createMenuItem("double length",pattern_menu,"double_length");
createMenuItem("triple length",pattern_menu,"triple_length");
//createMenuItem("transpose fifth",pattern_menu,"transpose_fifth_up");
//createMenuItem("transpose fourth",pattern_menu,"transpose_fourth_down");
createMenuItem("copy",pattern_menu,"menu_copy");
createMenuItem("paste",pattern_menu,"menu_paste");
createMenuItem("rename",pattern_menu,"menu_rename");
mb.add(pattern_menu);
JMenu song_menu = new JMenu("song");
//createMenuItem("show equalizer",song_menu,"equalizer");
createMenuItem("parametric equalizer",song_menu,"bass_treble");
createMenuItem("show pattern list",song_menu,"menu_pattern_list");
createMenuItem("get song length",song_menu,"get_song_length");
createMenuItem("show hex keyboard",song_menu,"show_hex_keyboard");
createMenuItem("edit envelope",song_menu,"edit_envelope");
createMenuItem("add random patterns",song_menu,"add_random_patterns");
mb.add(song_menu);
JMenu tunning_table_menu = new JMenu("table");
createMenuItem("view tunning table",tunning_table_menu,"view_tunning_table");
//createMenuItem("generate mean tone",tunning_table_menu,"generate_mean_tone_scale");
createMenuItem("create temperament",tunning_table_menu,"create_temperament");
createMenuItem("import scala",tunning_table_menu,"import_scala");
createMenuItem("export scala",tunning_table_menu,"export_scala");
mb.add(tunning_table_menu);
JMenu harmonics_menu = new JMenu("harmonics");
createMenuItem("edit harmonic colors",harmonics_menu,"edit_harmonic_colors");
createMenuItem("edit prime harmonics",harmonics_menu,"view_prime_table");
createMenuItem("options",harmonics_menu,"str_table_options");
mb.add(harmonics_menu);
return mb;
}
}
| add random melody
| main_app.java | add random melody | <ide><path>ain_app.java
<ide> }
<ide> return (int) (f3+0.5);
<ide> }
<add> void add_random_melody() {
<add> patternc p = main_app.song_player.pattern;
<add> Random rand = new Random();
<add> Rectangle r = main_panel_scroller.getViewport().getViewRect();
<add> int y2 = r.y / sqsize;
<add> int h = r.height / sqsize;
<add> for (int x = 0;x < p.length;x++) {
<add> int y = rand.nextInt(h)+y2;
<add> int a = p.get_cell(x,y);
<add> p.set_cell(x,y,a ^ pan_note);
<add> }
<add> main_frame.repaint();
<add> }
<ide>
<ide> void display_song_length() {
<ide> int total_length = 0;
<ide> }
<ide> if (action.equals("add_random_patterns")) {
<ide> add_random_patterns();
<add> }
<add> if (action.equals("add_random_melody")) {
<add> add_random_melody();
<ide> }
<ide> if (action.equals("view_prime_table")) {
<ide> if (prime_table_window == null) {
<ide>
<ide> }
<ide> static void update_status_bar() {
<del> String str = "volume: " + pattern_player.volume;
<add> String str = "volume: " + pattern_player.volume + "dB";
<ide> //str = str + " bass: " + pattern_player.bass;
<ide> //int o = num_octaves-octave_offset;
<ide> str = str + " pan: ";
<ide> createMenuItem("copy",pattern_menu,"menu_copy");
<ide> createMenuItem("paste",pattern_menu,"menu_paste");
<ide> createMenuItem("rename",pattern_menu,"menu_rename");
<add> createMenuItem("add random melody",pattern_menu,"add_random_melody");
<add>
<ide> mb.add(pattern_menu);
<ide> JMenu song_menu = new JMenu("song");
<ide> //createMenuItem("show equalizer",song_menu,"equalizer"); |
|
Java | mit | 127f82b1f469c9736ab244f1c8ac059738346b06 | 0 | solinor/paymenthighway-java-lib | package com.solinor.paymenthighway.model;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.solinor.paymenthighway.json.JsonParser;
public class ReportResponseTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
String json = "{\"settlements\":[{\"id\":\"11d22268-cc71-4894-bf41-e13a9039c327\",\"batch\":\"000016\",\"timestamp\":\"2015-03-20T22:00:09Z\",\"merchant\":{\"id\":\"test_merchantId\",\"name\":\"Test user\"},\"transaction_count\":1,\"net_amount\":320,\"currency\":\"EUR\",\"acquirer\":{\"id\":\"nets\",\"name\":\"Nets\"},\"transactions\":[{\"id\":\"f9a48e02-4301-49ff-a4f1-65749435924a\",\"timestamp\":\"2015-03-20T13:09:36Z\",\"type\":\"debit\",\"partial_pan\":\"0024\",\"amount\":320,\"currency\":\"EUR\",\"filing_code\":\"150320000263\",\"status\":{\"state\":\"ok\",\"code\":4000},\"authorization_code\":\"894463\"}],\"status\":{\"state\":\"ok\",\"code\":4000},\"reference\":\"11503201000000162\"}],\"result\":{\"code\":100,\"message\":\"OK\"}}";
JsonParser parser = new JsonParser();
ReportResponse response = parser.mapReportResponse(json);
assertEquals("100", response.getResult().getCode());
assertEquals("OK", response.getResult().getMessage());
Settlement[] settlements = response.getSettlements();
assertEquals(1, settlements.length);
Settlement settlement = settlements[0];
assertEquals("nets", settlement.getAcquirer().getId());
assertEquals("Nets", settlement.getAcquirer().getName());
assertEquals("000016", settlement.getBatch());
assertEquals("EUR", settlement.getCurrency());
assertEquals("11d22268-cc71-4894-bf41-e13a9039c327", settlement.getId().toString());
assertEquals("1", settlement.getTransactionCount());
assertEquals("Test user", settlement.getMerchant().getName());
assertEquals("test_merchantId", settlement.getMerchant().getId());
}
/**
* Robustness test. Unknown json fields should not cause issues.
*/
@Test
public void test2() {
String json = "{\"settlements\":[{\"id\":\"11d22268-cc71-4894-bf41-e13a9039c327\",\"batch\":\"000016\",\"timestamp\":\"2015-03-20T22:00:09Z\",\"merchant\":{\"id\":\"test_merchantId\",\"name\":\"Test user\"},\"transaction_count\":1,\"net_amount\":320,\"currency\":\"EUR\",\"acquirer\":{\"id\":\"nets\",\"name\":\"Nets\"},\"transactions\":[{\"id\":\"f9a48e02-4301-49ff-a4f1-65749435924a\",\"timestamp\":\"2015-03-20T13:09:36Z\",\"type\":\"debit\",\"partial_pan\":\"0024\",\"amount\":320,\"robustnesstest1\":true,\"robustnesstest2\":\"xxxxxx\",\"currency\":\"EUR\",\"filing_code\":\"150320000263\",\"status\":{\"state\":\"ok\",\"code\":4000},\"authorization_code\":\"894463\"}],\"status\":{\"state\":\"ok\",\"code\":4000},\"reference\":\"11503201000000162\"}],\"result\":{\"code\":100,\"message\":\"OK\"}}";
JsonParser parser = new JsonParser();
ReportResponse response = parser.mapReportResponse(json);
assertEquals("100", response.getResult().getCode());
assertEquals("OK", response.getResult().getMessage());
Settlement[] settlements = response.getSettlements();
assertEquals(1, settlements.length);
Settlement settlement = settlements[0];
assertEquals("nets", settlement.getAcquirer().getId());
assertEquals("Nets", settlement.getAcquirer().getName());
assertEquals("000016", settlement.getBatch());
assertEquals("EUR", settlement.getCurrency());
assertEquals("11d22268-cc71-4894-bf41-e13a9039c327", settlement.getId().toString());
assertEquals("1", settlement.getTransactionCount());
assertEquals("Test user", settlement.getMerchant().getName());
assertEquals("test_merchantId", settlement.getMerchant().getId());
}
}
| src/test/java/com/solinor/paymenthighway/model/ReportResponseTest.java | package com.solinor.paymenthighway.model;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.solinor.paymenthighway.json.JsonParser;
public class ReportResponseTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
String json = "{\"settlements\":[{\"id\":\"11d22268-cc71-4894-bf41-e13a9039c327\",\"batch\":\"000016\",\"timestamp\":\"2015-03-20T22:00:09Z\",\"merchant\":{\"id\":\"test_merchantId\",\"name\":\"Test user\"},\"transaction_count\":1,\"net_amount\":320,\"currency\":\"EUR\",\"acquirer\":{\"id\":\"nets\",\"name\":\"Nets\"},\"transactions\":[{\"id\":\"f9a48e02-4301-49ff-a4f1-65749435924a\",\"timestamp\":\"2015-03-20T13:09:36Z\",\"type\":\"debit\",\"partial_pan\":\"0024\",\"amount\":320,\"currency\":\"EUR\",\"filing_code\":\"150320000263\",\"status\":{\"state\":\"ok\",\"code\":4000},\"authorization_code\":\"894463\"}],\"status\":{\"state\":\"ok\",\"code\":4000},\"reference\":\"11503201000000162\"}],\"result\":{\"code\":100,\"message\":\"OK\"}}";
JsonParser parser = new JsonParser();
ReportResponse response = parser.mapReportResponse(json);
assertEquals("100", response.getResult().getCode());
assertEquals("OK", response.getResult().getMessage());
Settlement[] settlements = response.getSettlements();
assertEquals(1, settlements.length);
Settlement settlement = settlements[0];
assertEquals("nets", settlement.getAcquirer().getId());
assertEquals("Nets", settlement.getAcquirer().getName());
assertEquals("000016", settlement.getBatch());
assertEquals("EUR", settlement.getCurrency());
assertEquals("11d22268-cc71-4894-bf41-e13a9039c327", settlement.getId().toString());
assertEquals("1", settlement.getTransactionCount());
assertEquals("Test user", settlement.getMerchant().getName());
assertEquals("test_merchantId", settlement.getMerchant().getId());
}
}
| test for robust json parsing
| src/test/java/com/solinor/paymenthighway/model/ReportResponseTest.java | test for robust json parsing | <ide><path>rc/test/java/com/solinor/paymenthighway/model/ReportResponseTest.java
<ide> assertEquals("test_merchantId", settlement.getMerchant().getId());
<ide>
<ide> }
<add> /**
<add> * Robustness test. Unknown json fields should not cause issues.
<add> */
<add> @Test
<add> public void test2() {
<add> String json = "{\"settlements\":[{\"id\":\"11d22268-cc71-4894-bf41-e13a9039c327\",\"batch\":\"000016\",\"timestamp\":\"2015-03-20T22:00:09Z\",\"merchant\":{\"id\":\"test_merchantId\",\"name\":\"Test user\"},\"transaction_count\":1,\"net_amount\":320,\"currency\":\"EUR\",\"acquirer\":{\"id\":\"nets\",\"name\":\"Nets\"},\"transactions\":[{\"id\":\"f9a48e02-4301-49ff-a4f1-65749435924a\",\"timestamp\":\"2015-03-20T13:09:36Z\",\"type\":\"debit\",\"partial_pan\":\"0024\",\"amount\":320,\"robustnesstest1\":true,\"robustnesstest2\":\"xxxxxx\",\"currency\":\"EUR\",\"filing_code\":\"150320000263\",\"status\":{\"state\":\"ok\",\"code\":4000},\"authorization_code\":\"894463\"}],\"status\":{\"state\":\"ok\",\"code\":4000},\"reference\":\"11503201000000162\"}],\"result\":{\"code\":100,\"message\":\"OK\"}}";
<add>
<add> JsonParser parser = new JsonParser();
<add> ReportResponse response = parser.mapReportResponse(json);
<add>
<add> assertEquals("100", response.getResult().getCode());
<add> assertEquals("OK", response.getResult().getMessage());
<add>
<add> Settlement[] settlements = response.getSettlements();
<add>
<add> assertEquals(1, settlements.length);
<add>
<add> Settlement settlement = settlements[0];
<add>
<add> assertEquals("nets", settlement.getAcquirer().getId());
<add> assertEquals("Nets", settlement.getAcquirer().getName());
<add> assertEquals("000016", settlement.getBatch());
<add> assertEquals("EUR", settlement.getCurrency());
<add> assertEquals("11d22268-cc71-4894-bf41-e13a9039c327", settlement.getId().toString());
<add> assertEquals("1", settlement.getTransactionCount());
<add> assertEquals("Test user", settlement.getMerchant().getName());
<add> assertEquals("test_merchantId", settlement.getMerchant().getId());
<add>
<add> }
<ide> } |
|
Java | apache-2.0 | c4d49c081ad9e1fa41cd9d450163c7cde103a63d | 0 | junit-tools-team/junit-tools | package org.junit.tools.generator;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Vector;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IAnnotation;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMemberValuePair;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MemberValuePair;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.NormalAnnotation;
import org.eclipse.jdt.core.dom.StringLiteral;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.internal.core.Annotation;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
import org.junit.tools.base.MethodRef;
import org.junit.tools.generator.model.GeneratorModel;
import org.junit.tools.generator.model.JUTElements.JUTClassesAndPackages;
import org.junit.tools.generator.model.tml.Assertion;
import org.junit.tools.generator.model.tml.AssertionType;
import org.junit.tools.generator.model.tml.Constructor;
import org.junit.tools.generator.model.tml.Method;
import org.junit.tools.generator.model.tml.Mocks;
import org.junit.tools.generator.model.tml.Param;
import org.junit.tools.generator.model.tml.ParamAssignment;
import org.junit.tools.generator.model.tml.Result;
import org.junit.tools.generator.model.tml.Settings;
import org.junit.tools.generator.model.tml.Test;
import org.junit.tools.generator.model.tml.TestBase;
import org.junit.tools.generator.model.tml.TestBases;
import org.junit.tools.generator.model.tml.TestCase;
import org.junit.tools.generator.model.tml.Testprio;
import org.junit.tools.generator.utils.GeneratorUtils;
import org.junit.tools.generator.utils.JDTUtils;
import org.junit.tools.preferences.JUTPreferences;
/**
* The default test-class java generator. On the base of the TML the test-class
* will be generated.
*
* @author Robert Streng
*
* TODO generate with AST
*/
@SuppressWarnings("restriction")
// TODO avoid restrictions
public class TestClassGenerator implements ITestClassGenerator,
IGeneratorConstants {
protected String annoGenerated = null;
protected String testmethodPrefix;
protected String testmethodPostfix;
protected boolean defaultTestbaseMethodCreated = false;
@Override
public ICompilationUnit generate(GeneratorModel model,
List<ITestDataFactory> testDataFactories, IProgressMonitor monitor)
throws Exception {
boolean writeTML = JUTPreferences.isWriteTML();
defaultTestbaseMethodCreated = false;
Test tmlTest = model.getTmlTest();
Settings tmlSettings = tmlTest.getSettings();
JUTClassesAndPackages utmClassesAndPackages = model.getJUTElements()
.getClassesAndPackages();
ICompilationUnit testClass = utmClassesAndPackages.getTestClass(true);
String testClassName = utmClassesAndPackages.getTestClassName();
ICompilationUnit baseClass = utmClassesAndPackages.getBaseClass();
String baseClassName = utmClassesAndPackages.getBaseClassName();
IType type;
// begin task
int methodSize = tmlTest.getMethod().size();
int increment;
if (methodSize >= 300) {
increment = 50;
} else if (methodSize >= 100) {
increment = 30;
} else {
increment = 20;
}
methodSize = methodSize / increment;
monitor.beginTask("", 6 + methodSize);
// create or update test-class-frame
type = createTestClassFrame(testClass, tmlTest, testClassName);
// increment task
if (incrementTask(monitor))
return null;
// delete generated elements
if (testClass.exists()) {
deleteGeneratedElements(testClass, tmlSettings);
}
// increment task
if (incrementTask(monitor))
return null;
// create standard-imports
createStandardImports(testClass, tmlTest);
// increment task
if (incrementTask(monitor))
return null;
// create standard-class-fields
createStandardClassFields(type, tmlTest, testClassName);
// increment task
if (incrementTask(monitor))
return null;
// create standard-methods
createStandardMethods(type, tmlSettings);
// increment task
if (incrementTask(monitor))
return null;
// create test-base-methods
if (writeTML) {
createTestBaseMethods(type, tmlTest, baseClassName);
} else {
createTestBaseMethods(type, baseClass, baseClassName, model
.getJUTElements().getConstructorsAndMethods()
.getBaseClassConstructors(), testDataFactories);
}
// increment task
if (incrementTask(monitor))
return null;
// delete test-methods
for (IMethod methodToDelete : model.getMethodsToDelete()) {
methodToDelete.delete(true, null);
}
// create test-methods
if (createTestMethods(type, model.getMethodMap(),
model.getMethodsToCreate(), tmlSettings, baseClassName,
monitor, increment)) {
return null;
}
// update test-methods (method-ref)
updateExistingMethods(type.getCompilationUnit(), type,
model.getExistingMethods());
IPackageFragment testPackage = model.getJUTElements()
.getClassesAndPackages().getTestPackage();
testClass.createPackageDeclaration(testPackage.getElementName(), null);
// create static standard-imports
createStandardStaticImports(testClass);
// save test-class
testClass.save(null, true);
testClass.makeConsistent(null);
if (testClass.hasUnsavedChanges()) {
testClass.commitWorkingCopy(true, null);
}
return testClass;
}
@SuppressWarnings("unchecked")
protected void updateExistingMethods(ICompilationUnit cu, IType cuType,
HashMap<MethodRef, IMethod> existingMethods)
throws JavaModelException, IllegalArgumentException,
MalformedTreeException, BadLocationException {
MethodRef methodRef;
Annotation annotation;
for (Entry<MethodRef, IMethod> entry : existingMethods.entrySet()) {
// update method reference
methodRef = entry.getKey();
if (methodRef.isSignatureChanged()) {
// delete old annotation
for (IAnnotation iAnnotation : entry.getValue()
.getAnnotations()) {
if (iAnnotation instanceof Annotation) {
annotation = (Annotation) iAnnotation;
if (ANNO_METHOD_REF_NAME.equals(iAnnotation
.getElementName())) {
if (annotation.exists()) {
annotation.delete(true, null);
}
}
}
}
// create new annotation
CompilationUnit astRoot = JDTUtils.createASTRoot(cu);
MethodDeclaration md = JDTUtils.createMethodDeclaration(
astRoot, entry.getValue());
final ASTRewrite rewriter = ASTRewrite.create(md.getAST());
NormalAnnotation newNormalAnnotation = rewriter.getAST()
.newNormalAnnotation();
newNormalAnnotation.setTypeName(astRoot.getAST().newName(
"MethodRef"));
newNormalAnnotation.values().add(
createAnnotationMemberValuePair(astRoot.getAST(),
"name", methodRef.getName()));
newNormalAnnotation.values().add(
createAnnotationMemberValuePair(astRoot.getAST(),
"signature", methodRef.getSignatureNew()));
rewriter.getListRewrite(md,
MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(
newNormalAnnotation, null);
// apply changes
TextEdit textEdit = rewriter.rewriteAST();
Document document = new Document(cu.getSource());
textEdit.apply(document);
String newSource = document.get();
// update of the compilation unit
cu.getBuffer().setContents(newSource);
}
}
}
protected MemberValuePair createAnnotationMemberValuePair(final AST ast,
final String name, final String value) {
final MemberValuePair mvp = ast.newMemberValuePair();
mvp.setName(ast.newSimpleName(name));
StringLiteral stringLiteral = ast.newStringLiteral();
stringLiteral.setLiteralValue(value);
mvp.setValue(stringLiteral);
return mvp;
}
protected void createTestBaseMethods(IType type,
ICompilationUnit baseClass, String baseClassName,
Vector<IMethod> constructors,
List<ITestDataFactory> testDataFactories) throws JavaModelException {
String testBaseMethodBody;
StringBuilder classCreationChain;
classCreationChain = new StringBuilder();
String testBaseMethodName = "createTestSubject";
if (type.getMethod(testBaseMethodName, null).exists()) {
return;
}
JDTUtils.createClassCreationChain(baseClass.findPrimaryType(),
classCreationChain, testDataFactories);
testBaseMethodBody = " return " + classCreationChain.toString() + ";";
JDTUtils.createMethod(type, MOD_PRIVATE, baseClassName,
testBaseMethodName, null, null, testBaseMethodBody, false);
}
/**
* Creates test base methods.
*
* @param type
* @param tmlTest
* @param testBaseName
* @throws JavaModelException
*/
protected void createTestBaseMethods(IType type, Test tmlTest,
String testBaseName) throws JavaModelException {
Settings tmlSettings = tmlTest.getSettings();
TestBases tmlTestbases = tmlTest.getTestBases();
if (tmlSettings == null || tmlTestbases == null) {
return;
}
String testBaseMethodBody;
String testBaseMethodName;
for (Constructor tmlConstructor : tmlTestbases.getConstructor()) {
for (TestBase tmlTestbase : tmlConstructor.getTestBase()) {
testBaseMethodName = createTestBaseMethodName(tmlTestbase
.getName());
testBaseMethodBody = createTestBaseMethodBody(tmlTestbase,
testBaseName, testBaseMethodName,
tmlConstructor.getParam(), tmlSettings);
JDTUtils.createMethod(type, MOD_PRIVATE, testBaseName,
testBaseMethodName, "Exception", null,
testBaseMethodBody, false);
}
if (tmlConstructor.getTestBase().size() == 0) {
createTestBaseMethodDefault(type, testBaseName,
tmlConstructor.getParam());
}
}
}
/**
* Creates the standard methods.
*
* @param type
* @param tmlSettings
* @throws JavaModelException
*/
protected void createStandardMethods(IType type, Settings tmlSettings)
throws JavaModelException {
if (tmlSettings == null) {
return;
}
if (tmlSettings.isSetUp()) {
JDTUtils.createMethod(type, MOD_PUBLIC, TYPE_VOID,
STANDARD_METHOD_BEFORE, EXCEPTION, null, "", false,
ANNO_JUNIT_BEFORE);
}
if (tmlSettings.isSetUpBeforeClass()) {
JDTUtils.createMethod(type, MOD_PUBLIC + MOD_STATIC_WITH_BLANK,
TYPE_VOID, STANDARD_METHOD_BEFORE_ClASS, EXCEPTION, null,
"", false, ANNO_JUNIT_BEFORE_CLASS);
}
if (tmlSettings.isTearDown()) {
JDTUtils.createMethod(type, MOD_PUBLIC, TYPE_VOID,
STANDARD_METHOD_AFTER, EXCEPTION, null, "", false,
ANNO_JUNIT_AFTER);
}
if (tmlSettings.isTearDownBeforeClass()) {
JDTUtils.createMethod(type, MOD_PUBLIC + MOD_STATIC_WITH_BLANK,
TYPE_VOID, STANDARD_METHOD_AFTER_CLASS, "Exception", null,
"", false, ANNO_JUNIT_AFTER_CLASS);
}
}
/**
* Create a hook after a method call.
*
* @param type
* @param hookMethodName
* @param param
* @throws JavaModelException
*/
protected void createHookAfterMethodCall(IType type, String hookMethodName,
String param) throws JavaModelException {
JDTUtils.createMethod(type, MOD_PRIVATE, TYPE_VOID, hookMethodName,
"Exception", param, "", false);
}
/**
* Increments the task.
*
* @param monitor
* @return true if not canceled
*/
protected boolean incrementTask(IProgressMonitor monitor) {
return incrementTask(monitor, 1);
}
/**
* Increments the task.
*
* @param monitor
* @param i
* @return true if not canceled
*/
protected boolean incrementTask(IProgressMonitor monitor, int i) {
if (monitor.isCanceled())
return true;
monitor.worked(i);
return false;
}
/**
* Deletes the generated elements.
*
* @param testClass
* @param tmlSettings
* @throws JavaModelException
*/
protected void deleteGeneratedElements(ICompilationUnit testClass,
Settings tmlSettings) throws JavaModelException {
IType[] types = testClass.getTypes();
IMethod method;
IField field;
for (IType type : types) {
for (IJavaElement element : type.getChildren()) {
if (element instanceof IMethod) {
method = (IMethod) element;
if (!deleteStandardMethod(
method.getElementName().replace(".java", ""),
tmlSettings)) {
continue;
}
} else if (element instanceof IField) {
field = (IField) element;
if (isGenerated(field.getAnnotations())) {
field.delete(true, null);
}
}
}
}
}
/**
* @param tmlSettings
* @return isStandardMethod
*/
protected boolean deleteStandardMethod(String methodName,
Settings tmlSettings) {
if (STANDARD_METHOD_BEFORE.equals(methodName)) {
if (!tmlSettings.isSetUp()) {
return true;
} else {
return false;
}
} else if (STANDARD_METHOD_BEFORE_ClASS.equals(methodName)) {
if (!tmlSettings.isSetUpBeforeClass()) {
return true;
} else {
return false;
}
} else if (STANDARD_METHOD_AFTER.equals(methodName)) {
if (!tmlSettings.isTearDown()) {
return true;
} else {
return false;
}
} else if (STANDARD_METHOD_AFTER_CLASS.equals(methodName)) {
if (!tmlSettings.isTearDownBeforeClass()) {
return true;
} else {
return false;
}
}
return true;
}
/**
* Creates the test class frame.
*
* @param testCompilationUnit
* @param tmlTest
* @param testClassName
* @return the created test class frame
* @throws JavaModelException
*/
protected IType createTestClassFrame(ICompilationUnit testCompilationUnit,
Test tmlTest, String testClassName) throws JavaModelException {
IType type = testCompilationUnit.getType(testClassName);
if (!type.exists()) {
return createTestClassFrame(testCompilationUnit, tmlTest,
testClassName, null);
} else {
// check if recreation of test-class-frame is necessary
Vector<Annotation> annotationsToDelete = getAnnotationsToDelete(
type, tmlTest);
if (annotationsToDelete != null) {
for (Annotation annotation : annotationsToDelete)
annotation.delete(true, null);
String source = type.getSource();
type.delete(true, null);
return createTestClassFrame(testCompilationUnit, tmlTest,
testClassName, source);
}
}
return type;
}
/**
* Returns the annotation to delete.
*
* @param type
* @param tmlTest
* @throws JavaModelException
*/
protected Vector<Annotation> getAnnotationsToDelete(IType type, Test tmlTest)
throws JavaModelException {
Vector<Annotation> annotationsToDelete = new Vector<Annotation>();
Annotation annotation;
boolean recreationNecessary = false;
for (IAnnotation iAnnotation : type.getAnnotations()) {
if (iAnnotation instanceof Annotation) {
annotation = (Annotation) iAnnotation;
if (ANNO_GENERATED_NAME.equals(iAnnotation.getElementName())) {
annotationsToDelete.add(annotation);
IMemberValuePair[] memberValuePairs = annotation
.getMemberValuePairs();
for (IMemberValuePair valuePair : memberValuePairs) {
if (!VERSION.equals(valuePair.getValue())) {
recreationNecessary = true;
break;
}
}
} else if (ANNO_TESTPRIO_NAME.equals(iAnnotation
.getElementName())) {
annotationsToDelete.add(annotation);
IMemberValuePair[] memberValuePairs = annotation
.getMemberValuePairs();
if (memberValuePairs.length == 0) {
if (tmlTest.getTestPrio().compareTo(Testprio.DEFAULT) != 0)
recreationNecessary = true;
}
for (IMemberValuePair valuePair : memberValuePairs) {
if (!valuePair.getValue().toString()
.endsWith(tmlTest.getTestPrio().toString())) {
recreationNecessary = true;
break;
}
}
}
}
}
if (!recreationNecessary)
return null;
return annotationsToDelete;
}
/**
* Creates a test class frame.
*
* @param testCompilationUnit
* @param tmlTest
* @param testclassName
* @param source
* @return the created test class frame
* @throws JavaModelException
*/
protected IType createTestClassFrame(ICompilationUnit testCompilationUnit,
Test tmlTest, String testclassName, String source)
throws JavaModelException {
// create annotations
String annotations = createTestClassFrameAnnotations(tmlTest
.getTestPrio());
// create type
String superType = "";
if (source == null) {
String customComment = getTestClassComment();
superType = tmlTest.getSuperClass();
String extendsStmt = "";
if (!(superType == null || "".equals(superType))) {
extendsStmt = " extends " + superType;
} else {
superType = "";
}
source = customComment + annotations.toString() + MOD_PUBLIC
+ " class " + testclassName + extendsStmt + "{ " + RETURN
+ "}";
} else {
source = annotations + source;
}
IType type = testCompilationUnit.createType(source, null, true, null);
String superTypePackage = tmlTest.getSuperClassPackage();
if (!"".equals(superType) && superTypePackage != null
&& !"".equals(superTypePackage)) {
testCompilationUnit.createImport(
superTypePackage + "." + superType, null, null);
}
return type;
}
protected String getTestClassComment() {
return "";
}
/**
* Creates the test class annotations.
*
* @param testprio
* @return the created annotations
*/
protected String createTestClassFrameAnnotations(Testprio testprio) {
// create annotations
StringBuilder annotations = new StringBuilder();
// create generator-annotation
annotations.append(createAnnoGenerated());
// test-priority-annotation
annotations.append(createAnnoTestprio(testprio));
return annotations.toString();
}
/**
* Creates the annotation generated.
*
* @return the created annotation
*/
protected String createAnnoGenerated() {
if (annoGenerated == null) {
annoGenerated = GeneratorUtils.createAnnoGenerated();
}
return annoGenerated;
}
/**
* Creates the standard imports.
*
* @param compilationUnit
* @param tmlTest
* @throws JavaModelException
*/
protected void createStandardImports(ICompilationUnit compilationUnit,
Test tmlTest) throws JavaModelException {
compilationUnit.createImport("java.util.*", null, null);
compilationUnit.createImport("org.junit.Assert", null, null);
compilationUnit.createImport("org.junit.Test", null, null);
if (tmlTest.getSettings().isLogger()) {
compilationUnit
.createImport("java.util.logging.Logger", null, null);
}
}
protected void createStandardStaticImports(ICompilationUnit compilationUnit)
throws JavaModelException {
IJavaElement importAbove = null;
IImportDeclaration[] imports = compilationUnit.getImports();
if (imports.length > 0) {
importAbove = imports[0];
compilationUnit.createImport("org.junit.Assert.*", importAbove,
Flags.AccStatic, null);
}
}
/**
* Create standard class fields.
*
* @param type
* @param tmlTest
* @param testclassName
* @throws JavaModelException
*/
protected void createStandardClassFields(IType type, Test tmlTest,
String testclassName) throws JavaModelException {
if (tmlTest.getSettings().isLogger()) {
String logger = createAnnoGenerated() + " " + MOD_PRIVATE
+ " Logger logger = Logger.getLogger(" + testclassName
+ ".class.toString());";
type.createField(logger, null, false, null);
}
}
/**
* Creates the test base method with default values.
*
* @param type
* @param testbaseName
* @param params
* @throws JavaModelException
*/
protected void createTestBaseMethodDefault(IType type, String testbaseName,
List<Param> params) throws JavaModelException {
if (defaultTestbaseMethodCreated)
return;
String paramValueList;
if (params != null) {
paramValueList = createParamValueList(params, null);
} else {
paramValueList = "";
}
StringBuilder sbMethodBody = new StringBuilder();
sbMethodBody.append("return new ").append(testbaseName).append("(")
.append(paramValueList).append(");");
JDTUtils.createMethod(type, MOD_PRIVATE, testbaseName,
TESTSUBJECT_METHOD_PREFIX, null, null, sbMethodBody.toString());
defaultTestbaseMethodCreated = true;
}
/**
* Creates the test base method name.
*
* @param tmlTestBaseName
* @return test base method name
*/
protected String createTestBaseMethodName(String tmlTestBaseName) {
String testBaseName = GeneratorUtils.firstCharToUpper(tmlTestBaseName);
String testBaseMethodName = TESTSUBJECT_METHOD_PREFIX + testBaseName;
return testBaseMethodName;
}
/**
* Creates the test base method body.
*
* @param tmlTestbase
* @param testBaseName
* @param testBaseMethodName
* @param params
* @param tmlSettings
* @return the created test base method body
*/
protected String createTestBaseMethodBody(TestBase tmlTestbase,
String testBaseName, String testBaseMethodName, List<Param> params,
Settings tmlSettings) {
StringBuilder sbMethodBody = new StringBuilder();
String constructorParams = "";
if (params.size() > 0) {
constructorParams = createParamValueList(params,
tmlTestbase.getParamValue());
}
String testBaseMocks = createTestBaseMocks(tmlTestbase.getMocks());
String testBaseVariableName = GeneratorUtils
.firstCharToLower(testBaseName);
// test-base initialization
sbMethodBody.append(testBaseName).append(" ")
.append(testBaseVariableName).append("=").append("new ")
.append(testBaseName).append("(").append(constructorParams)
.append(") {").append(testBaseMocks).append("};")
.append(RETURN);
// return
sbMethodBody.append("return ").append(testBaseVariableName).append(";");
return sbMethodBody.toString();
}
/**
* Creates a parameter array list.
*
* @param params
* @return parameter array list
*/
protected String createParamArrayList(List<Param> params) {
StringBuilder sbParamArrayList = new StringBuilder();
boolean firstInit = true;
for (int i = 0; i < params.size(); i++) {
if (!firstInit) {
sbParamArrayList.append(",");
} else {
firstInit = false;
}
sbParamArrayList.append("(").append(params.get(i).getType())
.append(")paramList[").append(i).append("]");
}
return sbParamArrayList.toString();
}
/**
* Creates a parameter array list.
*
* @param params
* @param paramValues
* @return parameter array list
*/
protected String createParamArray(List<Param> params,
List<String> paramValues) {
StringBuilder sbParamArray = new StringBuilder();
boolean firstInit = true;
for (int i = 0; i < params.size() && i < paramValues.size(); i++) {
if (firstInit) {
sbParamArray.append("Object[] paramList = new Object[")
.append(params.size()).append("];");
firstInit = false;
}
sbParamArray
.append("paramList[")
.append(i)
.append("] = ")
.append(JDTUtils.formatValue(paramValues.get(i), params
.get(i).getType())).append(";").append(RETURN);
}
return sbParamArray.toString();
}
/**
* Creates the test base mocks.
*
* @param mocks
* @return test base mocks
*/
protected String createTestBaseMocks(Mocks mocks) {
if (mocks == null)
return "";
StringBuilder sbMockMethods = new StringBuilder();
String resultType;
String resultValue;
String modifier;
for (Method tmlMockMethod : mocks.getMethod()) {
if (tmlMockMethod.getResult() != null) {
resultType = tmlMockMethod.getResult().getType();
resultValue = tmlMockMethod.getResult().getValue();
resultValue = JDTUtils.formatValue(resultValue, resultType);
resultValue = "return " + resultValue + ";";
} else {
resultType = TYPE_VOID;
resultValue = "";
}
modifier = tmlMockMethod.getModifier();
if (MOD_PACKAGE.equals(modifier)) {
modifier = "";
}
sbMockMethods.append(modifier).append(" ").append(resultType)
.append(" ").append(tmlMockMethod.getName()).append("(")
.append(createParamList(tmlMockMethod.getParam()))
.append(") {").append(resultValue).append("}");
}
return sbMockMethods.toString();
}
/**
* Creates the test methods.
*
* @param type
* @param methodMap
* @param methodsToCreate
* @param tmlSettings
* @param baseClassName
* @param monitor
* @param increment
* @return true if the processing was stopped
* @throws JavaModelException
*/
protected boolean createTestMethods(IType type,
HashMap<IMethod, Method> methodMap, List<IMethod> methodsToCreate,
Settings tmlSettings, String baseClassName,
IProgressMonitor monitor, int increment) throws JavaModelException {
int i = 0;
boolean failAssertions = tmlSettings.isFailAssertions();
for (IMethod methodToCreate : methodsToCreate) {
Method tmlMethod = methodMap.get(methodToCreate);
createTestMethod(type, tmlMethod, baseClassName, failAssertions);
if (i++ == increment) {
i = 0;
// increment task
if (incrementTask(monitor))
return true;
}
}
return false;
}
/**
* Creates a test method.
*
* @param type
* @param tmlMethod
* @param baseClassName
* @param failAssertions
* @param hookAfterMethodCall
* @throws JavaModelException
*/
protected void createTestMethod(IType type, Method tmlMethod,
String baseClassName, boolean failAssertions)
throws JavaModelException {
String testMethodNamePrefix = getTestmethodPrefix();
String testMethodNamePostfix = getTestmethodPostfix();
String testMethodName;
String testMethodBody;
// create test-method-name
if (testMethodNamePrefix != null && testMethodNamePrefix.length() > 0) {
testMethodName = testMethodNamePrefix
+ GeneratorUtils.firstCharToUpper(tmlMethod.getName())
+ testMethodNamePostfix;
} else {
testMethodName = tmlMethod.getName() + testMethodNamePostfix;
}
// create test-method-body
testMethodBody = createTestMethodBody(type, tmlMethod, testMethodName,
baseClassName, failAssertions);
// create method ref
String annoMethodRef = GeneratorUtils.createAnnoMethodRef(
tmlMethod.getName(), tmlMethod.getSignature());
JDTUtils.createMethod(type, MOD_PUBLIC, TYPE_VOID, testMethodName,
"Exception", null, testMethodBody, true, annoMethodRef,
ANNO_JUNIT_TEST);
}
/**
* Creates the test method body.
*
* @param type
* @param tmlMethod
* @param methodName
* @param baseClassName
* @param failAssertions
* @param hookAfterMethodCall
* @return the created test method body
* @throws JavaModelException
*/
protected String createTestMethodBody(IType type, Method tmlMethod,
String methodName, String baseClassName, boolean failAssertions)
throws JavaModelException {
StringBuilder sbTestMethodBody = new StringBuilder();
List<Param> params = tmlMethod.getParam();
String testbaseMethodName = "";
String testBaseVariableName = "testSubject"; // GeneratorUtils.firstCharToLower(baseClassName);
// test-base-variable
if (!tmlMethod.isStatic()) {
sbTestMethodBody.append(baseClassName).append(" ")
.append(testBaseVariableName).append(";");
}
// create param initializations
createParamInitializations(params, sbTestMethodBody);
// create result-variable
Result result = tmlMethod.getResult();
String resultVariableName = "";
String resultType = "";
if (result != null) {
resultVariableName = result.getName();
resultType = result.getType();
sbTestMethodBody.append(resultType).append(" ")
.append(resultVariableName).append(";");
}
List<TestCase> testCases = tmlMethod.getTestCase();
boolean isPublic = MOD_PUBLIC.equals(tmlMethod.getModifier());
for (TestCase tmlTestcase : testCases) {
sbTestMethodBody.append(RETURN + RETURN + "// ")
.append(tmlTestcase.getName()).append(RETURN);
testbaseMethodName = createTestBaseMethodName(tmlTestcase
.getTestBase());
createTestCaseBody(sbTestMethodBody, tmlMethod.getName(),
baseClassName, testBaseVariableName, testbaseMethodName,
resultVariableName, resultType, params,
tmlTestcase.getParamAssignments(), isPublic,
tmlMethod.isStatic());
// assertions
createAssertionsMethodBody(sbTestMethodBody, resultVariableName,
resultType, testBaseVariableName, tmlTestcase);
}
// fail-assertion
if (failAssertions) {
sbTestMethodBody.append(RETURN + RETURN).append(FAIL_ASSERTION);
}
return sbTestMethodBody.toString();
}
/**
* Creates the test method body.
*
* @param sbTestMethodBody
* @param methodName
* @param baseClassName
* @param testBaseVariableName
* @param testBaseMethodName
* @param resultVariableName
* @param resultType
* @param params
* @param paramAssignments
* @param isPublic
* @param isStatic
*/
protected void createTestCaseBody(StringBuilder sbTestMethodBody,
String methodName, String baseClassName,
String testBaseVariableName, String testBaseMethodName,
String resultVariableName, String resultType, List<Param> params,
List<ParamAssignment> paramAssignments, boolean isPublic,
boolean isStatic) {
String baseName;
// create test-base
if (!isStatic) {
baseName = testBaseVariableName;
sbTestMethodBody.append(testBaseVariableName).append("=")
.append(testBaseMethodName).append("();");
} else {
baseName = baseClassName;
}
// create param assignments
createParamAssignments(paramAssignments, sbTestMethodBody);
// create param-list
String paramNameList = createParamNameList(params);
// result
if (resultVariableName.length() > 0) {
sbTestMethodBody.append(resultVariableName).append("=");
}
if (isPublic) {
// method-call
sbTestMethodBody.append(baseName).append(".").append(methodName)
.append("(").append(paramNameList).append(");");
} else {
// method-call with white-box-call
if (paramNameList.length() > 0) {
paramNameList = ", new Object[]{" + paramNameList + "}";
}
if (isStatic) {
baseName += ".class";
}
// TODO abfrage ob powermock oder jmockit
// sbTestMethodBody.append("Whitebox.invokeMethod(").append(baseName).append(", ").append(QUOTES)
// .append(methodName).append(QUOTES).append(paramValueList).append(");");
sbTestMethodBody.append("Deencapsulation.invoke(").append(baseName)
.append(", ").append(QUOTES).append(methodName)
.append(QUOTES).append(paramNameList).append(");");
}
}
protected String createParamNameList(List<Param> params) {
StringBuilder sbParamList = new StringBuilder();
String comma = "";
for (Param param : params) {
sbParamList.append(comma);
sbParamList.append(param.getName());
comma = ", ";
}
return sbParamList.toString();
}
protected void createParamInitializations(List<Param> params,
StringBuilder methodBody) {
// variable declaration and default initialization
for (Param param : params) {
methodBody.append(param.getType()).append(" ")
.append(param.getName()).append(" = ")
.append(JDTUtils.createInitValue(param.getType(), true))
.append(";").append(RETURN);
}
}
/**
* Creates the param assignments
*
* @param paramAssignments
* @param methodBody
*/
protected void createParamAssignments(
List<ParamAssignment> paramAssignments, StringBuilder methodBody) {
for (ParamAssignment pa : paramAssignments) {
methodBody.append(pa.getParamName()).append(" = ")
.append(pa.getAssignment()).append(";\n");
}
}
/**
* Creates the method body for the assertions.
*
* @param sbTestMethodBody
* @param resultVariableName
* @param resultType
* @param testBaseVariableName
* @param tmlTestCase
*/
protected void createAssertionsMethodBody(StringBuilder sbTestMethodBody,
String resultVariableName, String resultType,
String testBaseVariableName, TestCase tmlTestCase) {
String baseType;
for (Assertion tmlAssertion : tmlTestCase.getAssertion()) {
// base
String base;
if ("{result}".equals(tmlAssertion.getBase())) {
if ("".equals(resultVariableName)) {
continue;
}
base = "result";
baseType = resultType;
} else {
base = testBaseVariableName + "." + tmlAssertion.getBase()
+ "()";
baseType = tmlAssertion.getBaseType();
}
// assertion-type
AssertionType type = tmlAssertion.getType();
String assertionType = createAssertionType(type, baseType);
// Assertion
sbTestMethodBody.append(RETURN + "Assert.").append(assertionType)
.append("(");
// message
String message = "";
if (tmlAssertion.getMessage() != null
&& tmlAssertion.getMessage().length() > 0) {
message = tmlTestCase.getName() + ": "
+ tmlAssertion.getMessage();
sbTestMethodBody.append(QUOTES).append(message).append(QUOTES)
.append(", ");
}
// actual
if (type == AssertionType.EQUALS
|| type == AssertionType.NOT_EQUALS) {
// test-value
String testValue = tmlAssertion.getValue();
testValue = JDTUtils.formatValue(testValue, baseType);
sbTestMethodBody.append(testValue).append(", ");
// expected
sbTestMethodBody.append(base);
// delta
if (JDTUtils.isNumber(baseType) && !JDTUtils.isArray(baseType)) {
sbTestMethodBody.append(", 0");
}
} else {
// expected
sbTestMethodBody.append(base);
}
sbTestMethodBody.append(");");
}
}
/**
* Returns the assertion as String.
*
* @param type
* @param baseType
* @return assertion as String
*/
protected String createAssertionType(AssertionType type, String baseType) {
String assertionType = "assertEquals";
if (type == AssertionType.EQUALS) {
if (JDTUtils.isArray(baseType)) {
assertionType = "assertArrayEquals";
} else {
assertionType = "assertEquals";
}
} else if (type == AssertionType.NOT_EQUALS) {
assertionType = "assertNotEquals";
} else if (type == AssertionType.IS_NULL) {
assertionType = "assertNull";
} else if (type == AssertionType.NOT_NULL) {
assertionType = "assertNotNull";
} else if (type == AssertionType.IS_TRUE) {
assertionType = "assertTrue";
} else if (type == AssertionType.IS_FALSE) {
assertionType = "assertFalse";
}
return assertionType;
}
/**
* Creates a parameter list.
*
* @param params
* @return the created parameter list
*/
protected String createParamList(List<Param> params) {
Param tmlParam;
StringBuilder sbParamList = new StringBuilder();
boolean firstInit = true;
for (int i = 0; i < params.size(); i++) {
if (!firstInit)
sbParamList.append(", ");
else
firstInit = false;
tmlParam = params.get(i);
sbParamList.append(tmlParam.getType()).append(" ")
.append(tmlParam.getName());
}
return sbParamList.toString();
}
/**
* Creates a parameter list with values.
*
* @param params
* @param paramValues
* @return the created parameter list with values
*/
protected String createParamValueList(List<Param> params,
List<String> paramValues) {
StringBuilder sbParamList = new StringBuilder();
boolean firstInit = true;
Param tmlParam;
String value, type;
for (int i = 0; i < params.size()
&& (paramValues == null || i < paramValues.size()); i++) {
if (!firstInit)
sbParamList.append(", ");
else
firstInit = false;
tmlParam = params.get(i);
type = tmlParam.getType();
if (paramValues != null) {
value = paramValues.get(i);
} else {
value = "";
}
value = JDTUtils.formatValue(value, type);
sbParamList.append(value);
}
return sbParamList.toString();
}
protected String getTestmethodPrefix() {
if (testmethodPrefix == null)
testmethodPrefix = JUTPreferences.getTestMethodPrefix();
return testmethodPrefix;
}
/**
* @return the test method post fix
*/
protected String getTestmethodPostfix() {
if (testmethodPostfix == null)
testmethodPostfix = JUTPreferences.getTestMethodPostfix();
return testmethodPostfix;
}
/**
* Creates the annotation test priority.
*
* @return the created annotations
*/
protected String createAnnoTestprio(Testprio testprio) {
if (testprio == Testprio.DEFAULT)
return ANNO_TESTPRIO + RETURN;
return ANNO_TESTPRIO
+ "(prio=org.junit.tools.generator.model.tml.Testprio."
+ testprio + ")" + RETURN;
}
/**
* Returns if the annotation generated is set.
*
* @param annotations
* @return true if the annotation for the generated hooks is set.
*/
protected boolean isGenerated(IAnnotation[] annotations) {
for (IAnnotation annotation : annotations) {
if (ANNO_GENERATED_NAME.equals(annotation.getElementName()))
return true;
}
return false;
}
}
| org.junit.tools/src/org/junit/tools/generator/TestClassGenerator.java | package org.junit.tools.generator;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Vector;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IAnnotation;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMemberValuePair;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MemberValuePair;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.NormalAnnotation;
import org.eclipse.jdt.core.dom.StringLiteral;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.internal.core.Annotation;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
import org.junit.tools.base.MethodRef;
import org.junit.tools.generator.model.GeneratorModel;
import org.junit.tools.generator.model.JUTElements.JUTClassesAndPackages;
import org.junit.tools.generator.model.tml.Assertion;
import org.junit.tools.generator.model.tml.AssertionType;
import org.junit.tools.generator.model.tml.Constructor;
import org.junit.tools.generator.model.tml.Method;
import org.junit.tools.generator.model.tml.Mocks;
import org.junit.tools.generator.model.tml.Param;
import org.junit.tools.generator.model.tml.ParamAssignment;
import org.junit.tools.generator.model.tml.Result;
import org.junit.tools.generator.model.tml.Settings;
import org.junit.tools.generator.model.tml.Test;
import org.junit.tools.generator.model.tml.TestBase;
import org.junit.tools.generator.model.tml.TestBases;
import org.junit.tools.generator.model.tml.TestCase;
import org.junit.tools.generator.model.tml.Testprio;
import org.junit.tools.generator.utils.GeneratorUtils;
import org.junit.tools.generator.utils.JDTUtils;
import org.junit.tools.preferences.JUTPreferences;
/**
* The default test-class java generator. On the base of the TML the test-class
* will be generated.
*
* @author Robert Streng
*
* TODO generate with AST
*/
@SuppressWarnings("restriction")
// TODO avoid restrictions
public class TestClassGenerator implements ITestClassGenerator,
IGeneratorConstants {
protected String annoGenerated = null;
protected String testmethodPrefix;
protected String testmethodPostfix;
protected boolean defaultTestbaseMethodCreated = false;
@Override
public ICompilationUnit generate(GeneratorModel model,
List<ITestDataFactory> testDataFactories, IProgressMonitor monitor)
throws Exception {
boolean writeTML = JUTPreferences.isWriteTML();
defaultTestbaseMethodCreated = false;
Test tmlTest = model.getTmlTest();
Settings tmlSettings = tmlTest.getSettings();
JUTClassesAndPackages utmClassesAndPackages = model.getJUTElements()
.getClassesAndPackages();
ICompilationUnit testClass = utmClassesAndPackages.getTestClass(true);
String testClassName = utmClassesAndPackages.getTestClassName();
ICompilationUnit baseClass = utmClassesAndPackages.getBaseClass();
String baseClassName = utmClassesAndPackages.getBaseClassName();
IType type;
// begin task
int methodSize = tmlTest.getMethod().size();
int increment;
if (methodSize >= 300) {
increment = 50;
} else if (methodSize >= 100) {
increment = 30;
} else {
increment = 20;
}
methodSize = methodSize / increment;
monitor.beginTask("", 6 + methodSize);
// create or update test-class-frame
type = createTestClassFrame(testClass, tmlTest, testClassName);
// increment task
if (incrementTask(monitor))
return null;
// delete generated elements
if (testClass.exists()) {
deleteGeneratedElements(testClass, tmlSettings);
}
// increment task
if (incrementTask(monitor))
return null;
// create standard-imports
createStandardImports(testClass, tmlTest);
// increment task
if (incrementTask(monitor))
return null;
// create standard-class-fields
createStandardClassFields(type, tmlTest, testClassName);
// increment task
if (incrementTask(monitor))
return null;
// create standard-methods
createStandardMethods(type, tmlSettings);
// increment task
if (incrementTask(monitor))
return null;
// create test-base-methods
if (writeTML) {
createTestBaseMethods(type, tmlTest, baseClassName);
} else {
createTestBaseMethods(type, baseClass, baseClassName, model
.getJUTElements().getConstructorsAndMethods()
.getBaseClassConstructors(), testDataFactories);
}
// increment task
if (incrementTask(monitor))
return null;
// delete test-methods
for (IMethod methodToDelete : model.getMethodsToDelete()) {
methodToDelete.delete(true, null);
}
// create test-methods
if (createTestMethods(type, model.getMethodMap(),
model.getMethodsToCreate(), tmlSettings, baseClassName,
monitor, increment)) {
return null;
}
// update test-methods (method-ref)
updateExistingMethods(type.getCompilationUnit(), type,
model.getExistingMethods());
IPackageFragment testPackage = model.getJUTElements()
.getClassesAndPackages().getTestPackage();
testClass.createPackageDeclaration(testPackage.getElementName(), null);
// create static standard-imports
createStandardStaticImports(testClass);
// save test-class
testClass.save(null, true);
testClass.makeConsistent(null);
if (testClass.hasUnsavedChanges()) {
testClass.commitWorkingCopy(true, null);
}
return testClass;
}
@SuppressWarnings("unchecked")
protected void updateExistingMethods(ICompilationUnit cu, IType cuType,
HashMap<MethodRef, IMethod> existingMethods)
throws JavaModelException, IllegalArgumentException,
MalformedTreeException, BadLocationException {
MethodRef methodRef;
Annotation annotation;
for (Entry<MethodRef, IMethod> entry : existingMethods.entrySet()) {
// update method reference
methodRef = entry.getKey();
if (methodRef.isSignatureChanged()) {
// delete old annotation
for (IAnnotation iAnnotation : entry.getValue()
.getAnnotations()) {
if (iAnnotation instanceof Annotation) {
annotation = (Annotation) iAnnotation;
if (ANNO_METHOD_REF_NAME.equals(iAnnotation
.getElementName())) {
if (annotation.exists()) {
annotation.delete(true, null);
}
}
}
}
// create new annotation
CompilationUnit astRoot = JDTUtils.createASTRoot(cu);
MethodDeclaration md = JDTUtils.createMethodDeclaration(
astRoot, entry.getValue());
final ASTRewrite rewriter = ASTRewrite.create(md.getAST());
NormalAnnotation newNormalAnnotation = rewriter.getAST()
.newNormalAnnotation();
newNormalAnnotation.setTypeName(astRoot.getAST().newName(
"MethodRef"));
newNormalAnnotation.values().add(
createAnnotationMemberValuePair(astRoot.getAST(),
"name", methodRef.getName()));
newNormalAnnotation.values().add(
createAnnotationMemberValuePair(astRoot.getAST(),
"signature", methodRef.getSignatureNew()));
rewriter.getListRewrite(md,
MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(
newNormalAnnotation, null);
// apply changes
TextEdit textEdit = rewriter.rewriteAST();
Document document = new Document(cu.getSource());
textEdit.apply(document);
String newSource = document.get();
// update of the compilation unit
cu.getBuffer().setContents(newSource);
}
}
}
protected MemberValuePair createAnnotationMemberValuePair(final AST ast,
final String name, final String value) {
final MemberValuePair mvp = ast.newMemberValuePair();
mvp.setName(ast.newSimpleName(name));
StringLiteral stringLiteral = ast.newStringLiteral();
stringLiteral.setLiteralValue(value);
mvp.setValue(stringLiteral);
return mvp;
}
protected void createTestBaseMethods(IType type,
ICompilationUnit baseClass, String baseClassName,
Vector<IMethod> constructors,
List<ITestDataFactory> testDataFactories) throws JavaModelException {
String testBaseMethodBody;
StringBuilder classCreationChain;
classCreationChain = new StringBuilder();
String testBaseMethodName = "createTestSubject";
if (type.getMethod(testBaseMethodName, null).exists()) {
return;
}
JDTUtils.createClassCreationChain(baseClass.findPrimaryType(),
classCreationChain, testDataFactories);
testBaseMethodBody = " return " + classCreationChain.toString() + ";";
JDTUtils.createMethod(type, MOD_PRIVATE, baseClassName,
testBaseMethodName, null, null, testBaseMethodBody, false);
}
/**
* Creates test base methods.
*
* @param type
* @param tmlTest
* @param testBaseName
* @throws JavaModelException
*/
protected void createTestBaseMethods(IType type, Test tmlTest,
String testBaseName) throws JavaModelException {
Settings tmlSettings = tmlTest.getSettings();
TestBases tmlTestbases = tmlTest.getTestBases();
if (tmlSettings == null || tmlTestbases == null) {
return;
}
String testBaseMethodBody;
String testBaseMethodName;
for (Constructor tmlConstructor : tmlTestbases.getConstructor()) {
for (TestBase tmlTestbase : tmlConstructor.getTestBase()) {
testBaseMethodName = createTestBaseMethodName(tmlTestbase
.getName());
testBaseMethodBody = createTestBaseMethodBody(tmlTestbase,
testBaseName, testBaseMethodName,
tmlConstructor.getParam(), tmlSettings);
JDTUtils.createMethod(type, MOD_PRIVATE, testBaseName,
testBaseMethodName, "Exception", null,
testBaseMethodBody, false);
}
if (tmlConstructor.getTestBase().size() == 0) {
createTestBaseMethodDefault(type, testBaseName,
tmlConstructor.getParam());
}
}
}
/**
* Creates the standard methods.
*
* @param type
* @param tmlSettings
* @throws JavaModelException
*/
protected void createStandardMethods(IType type, Settings tmlSettings)
throws JavaModelException {
if (tmlSettings == null) {
return;
}
if (tmlSettings.isSetUp()) {
JDTUtils.createMethod(type, MOD_PUBLIC, TYPE_VOID,
STANDARD_METHOD_BEFORE, EXCEPTION, null, "", false,
ANNO_JUNIT_BEFORE);
}
if (tmlSettings.isSetUpBeforeClass()) {
JDTUtils.createMethod(type, MOD_PUBLIC + MOD_STATIC_WITH_BLANK,
TYPE_VOID, STANDARD_METHOD_BEFORE_ClASS, EXCEPTION, null,
"", false, ANNO_JUNIT_BEFORE_CLASS);
}
if (tmlSettings.isTearDown()) {
JDTUtils.createMethod(type, MOD_PUBLIC, TYPE_VOID,
STANDARD_METHOD_AFTER, EXCEPTION, null, "", false,
ANNO_JUNIT_AFTER);
}
if (tmlSettings.isTearDownBeforeClass()) {
JDTUtils.createMethod(type, MOD_PUBLIC + MOD_STATIC_WITH_BLANK,
TYPE_VOID, STANDARD_METHOD_AFTER_CLASS, "Exception", null,
"", false, ANNO_JUNIT_AFTER_CLASS);
}
}
/**
* Create a hook after a method call.
*
* @param type
* @param hookMethodName
* @param param
* @throws JavaModelException
*/
protected void createHookAfterMethodCall(IType type, String hookMethodName,
String param) throws JavaModelException {
JDTUtils.createMethod(type, MOD_PRIVATE, TYPE_VOID, hookMethodName,
"Exception", param, "", false);
}
/**
* Increments the task.
*
* @param monitor
* @return true if not canceled
*/
protected boolean incrementTask(IProgressMonitor monitor) {
return incrementTask(monitor, 1);
}
/**
* Increments the task.
*
* @param monitor
* @param i
* @return true if not canceled
*/
protected boolean incrementTask(IProgressMonitor monitor, int i) {
if (monitor.isCanceled())
return true;
monitor.worked(i);
return false;
}
/**
* Deletes the generated elements.
*
* @param testClass
* @param tmlSettings
* @throws JavaModelException
*/
protected void deleteGeneratedElements(ICompilationUnit testClass,
Settings tmlSettings) throws JavaModelException {
IType[] types = testClass.getTypes();
IMethod method;
IField field;
for (IType type : types) {
for (IJavaElement element : type.getChildren()) {
if (element instanceof IMethod) {
method = (IMethod) element;
if (!deleteStandardMethod(
method.getElementName().replace(".java", ""),
tmlSettings)) {
continue;
}
} else if (element instanceof IField) {
field = (IField) element;
if (isGenerated(field.getAnnotations())) {
field.delete(true, null);
}
}
}
}
}
/**
* @param tmlSettings
* @return isStandardMethod
*/
protected boolean deleteStandardMethod(String methodName,
Settings tmlSettings) {
if (STANDARD_METHOD_BEFORE.equals(methodName)) {
if (!tmlSettings.isSetUp()) {
return true;
} else {
return false;
}
} else if (STANDARD_METHOD_BEFORE_ClASS.equals(methodName)) {
if (!tmlSettings.isSetUpBeforeClass()) {
return true;
} else {
return false;
}
} else if (STANDARD_METHOD_AFTER.equals(methodName)) {
if (!tmlSettings.isTearDown()) {
return true;
} else {
return false;
}
} else if (STANDARD_METHOD_AFTER_CLASS.equals(methodName)) {
if (!tmlSettings.isTearDownBeforeClass()) {
return true;
} else {
return false;
}
}
return true;
}
/**
* Creates the test class frame.
*
* @param testCompilationUnit
* @param tmlTest
* @param testClassName
* @return the created test class frame
* @throws JavaModelException
*/
protected IType createTestClassFrame(ICompilationUnit testCompilationUnit,
Test tmlTest, String testClassName) throws JavaModelException {
IType type = testCompilationUnit.getType(testClassName);
if (!type.exists()) {
return createTestClassFrame(testCompilationUnit, tmlTest,
testClassName, null);
} else {
// check if recreation of test-class-frame is necessary
Vector<Annotation> annotationsToDelete = getAnnotationsToDelete(
type, tmlTest);
if (annotationsToDelete != null) {
for (Annotation annotation : annotationsToDelete)
annotation.delete(true, null);
String source = type.getSource();
type.delete(true, null);
return createTestClassFrame(testCompilationUnit, tmlTest,
testClassName, source);
}
}
return type;
}
/**
* Returns the annotation to delete.
*
* @param type
* @param tmlTest
* @throws JavaModelException
*/
protected Vector<Annotation> getAnnotationsToDelete(IType type, Test tmlTest)
throws JavaModelException {
Vector<Annotation> annotationsToDelete = new Vector<Annotation>();
Annotation annotation;
boolean recreationNecessary = false;
for (IAnnotation iAnnotation : type.getAnnotations()) {
if (iAnnotation instanceof Annotation) {
annotation = (Annotation) iAnnotation;
if (ANNO_GENERATED_NAME.equals(iAnnotation.getElementName())) {
annotationsToDelete.add(annotation);
IMemberValuePair[] memberValuePairs = annotation
.getMemberValuePairs();
for (IMemberValuePair valuePair : memberValuePairs) {
if (!VERSION.equals(valuePair.getValue())) {
recreationNecessary = true;
break;
}
}
} else if (ANNO_TESTPRIO_NAME.equals(iAnnotation
.getElementName())) {
annotationsToDelete.add(annotation);
IMemberValuePair[] memberValuePairs = annotation
.getMemberValuePairs();
if (memberValuePairs.length == 0) {
if (tmlTest.getTestPrio().compareTo(Testprio.DEFAULT) != 0)
recreationNecessary = true;
}
for (IMemberValuePair valuePair : memberValuePairs) {
if (!valuePair.getValue().toString()
.endsWith(tmlTest.getTestPrio().toString())) {
recreationNecessary = true;
break;
}
}
}
}
}
if (!recreationNecessary)
return null;
return annotationsToDelete;
}
/**
* Creates a test class frame.
*
* @param testCompilationUnit
* @param tmlTest
* @param testclassName
* @param source
* @return the created test class frame
* @throws JavaModelException
*/
protected IType createTestClassFrame(ICompilationUnit testCompilationUnit,
Test tmlTest, String testclassName, String source)
throws JavaModelException {
// create annotations
String annotations = createTestClassFrameAnnotations(tmlTest
.getTestPrio());
// create type
String superType = "";
if (source == null) {
String customComment = getTestClassComment();
superType = tmlTest.getSuperClass();
String extendsStmt = "";
if (!(superType == null || "".equals(superType))) {
extendsStmt = " extends " + superType;
} else {
superType = "";
}
source = customComment + annotations.toString() + MOD_PUBLIC
+ " class " + testclassName + extendsStmt + "{ " + RETURN
+ "}";
} else {
source = annotations + source;
}
IType type = testCompilationUnit.createType(source, null, true, null);
String superTypePackage = tmlTest.getSuperClassPackage();
if (!"".equals(superType) && superTypePackage != null
&& !"".equals(superTypePackage)) {
testCompilationUnit.createImport(
superTypePackage + "." + superType, null, null);
}
return type;
}
protected String getTestClassComment() {
return "";
}
/**
* Creates the test class annotations.
*
* @param testprio
* @return the created annotations
*/
protected String createTestClassFrameAnnotations(Testprio testprio) {
// create annotations
StringBuilder annotations = new StringBuilder();
// create generator-annotation
annotations.append(createAnnoGenerated());
// test-priority-annotation
annotations.append(createAnnoTestprio(testprio));
return annotations.toString();
}
/**
* Creates the annotation generated.
*
* @return the created annotation
*/
protected String createAnnoGenerated() {
if (annoGenerated == null) {
annoGenerated = GeneratorUtils.createAnnoGenerated();
}
return annoGenerated;
}
/**
* Creates the standard imports.
*
* @param compilationUnit
* @param tmlTest
* @throws JavaModelException
*/
protected void createStandardImports(ICompilationUnit compilationUnit,
Test tmlTest) throws JavaModelException {
compilationUnit.createImport("java.util.*", null, null);
compilationUnit.createImport("org.junit.Assert", null, null);
compilationUnit.createImport("org.junit.Test", null, null);
if (tmlTest.getSettings().isLogger()) {
compilationUnit
.createImport("java.util.logging.Logger", null, null);
}
}
protected void createStandardStaticImports(ICompilationUnit compilationUnit)
throws JavaModelException {
IJavaElement importAbove = null;
IImportDeclaration[] imports = compilationUnit.getImports();
if (imports.length > 0) {
importAbove = imports[0];
compilationUnit.createImport("org.junit.Assert.*", importAbove,
Flags.AccStatic, null);
}
}
/**
* Create standard class fields.
*
* @param type
* @param tmlTest
* @param testclassName
* @throws JavaModelException
*/
protected void createStandardClassFields(IType type, Test tmlTest,
String testclassName) throws JavaModelException {
if (tmlTest.getSettings().isLogger()) {
String logger = createAnnoGenerated() + " " + MOD_PRIVATE
+ " Logger logger = Logger.getLogger(" + testclassName
+ ".class.toString());";
type.createField(logger, null, false, null);
}
}
/**
* Creates the test base method with default values.
*
* @param type
* @param testbaseName
* @param params
* @throws JavaModelException
*/
protected void createTestBaseMethodDefault(IType type, String testbaseName,
List<Param> params) throws JavaModelException {
if (defaultTestbaseMethodCreated)
return;
String paramValueList;
if (params != null) {
paramValueList = createParamValueList(params, null);
} else {
paramValueList = "";
}
StringBuilder sbMethodBody = new StringBuilder();
sbMethodBody.append("return new ").append(testbaseName).append("(")
.append(paramValueList).append(");");
JDTUtils.createMethod(type, MOD_PRIVATE, testbaseName,
TESTSUBJECT_METHOD_PREFIX, null, null, sbMethodBody.toString());
defaultTestbaseMethodCreated = true;
}
/**
* Creates the test base method name.
*
* @param tmlTestBaseName
* @return test base method name
*/
protected String createTestBaseMethodName(String tmlTestBaseName) {
String testBaseName = GeneratorUtils.firstCharToUpper(tmlTestBaseName);
String testBaseMethodName = TESTSUBJECT_METHOD_PREFIX + testBaseName;
return testBaseMethodName;
}
/**
* Creates the test base method body.
*
* @param tmlTestbase
* @param testBaseName
* @param testBaseMethodName
* @param params
* @param tmlSettings
* @return the created test base method body
*/
protected String createTestBaseMethodBody(TestBase tmlTestbase,
String testBaseName, String testBaseMethodName, List<Param> params,
Settings tmlSettings) {
StringBuilder sbMethodBody = new StringBuilder();
String constructorParams = "";
if (params.size() > 0) {
constructorParams = createParamValueList(params,
tmlTestbase.getParamValue());
}
String testBaseMocks = createTestBaseMocks(tmlTestbase.getMocks());
String testBaseVariableName = GeneratorUtils
.firstCharToLower(testBaseName);
// test-base initialization
sbMethodBody.append(testBaseName).append(" ")
.append(testBaseVariableName).append("=").append("new ")
.append(testBaseName).append("(").append(constructorParams)
.append(") {").append(testBaseMocks).append("};")
.append(RETURN);
// return
sbMethodBody.append("return ").append(testBaseVariableName).append(";");
return sbMethodBody.toString();
}
/**
* Creates a parameter array list.
*
* @param params
* @return parameter array list
*/
protected String createParamArrayList(List<Param> params) {
StringBuilder sbParamArrayList = new StringBuilder();
boolean firstInit = true;
for (int i = 0; i < params.size(); i++) {
if (!firstInit) {
sbParamArrayList.append(",");
} else {
firstInit = false;
}
sbParamArrayList.append("(").append(params.get(i).getType())
.append(")paramList[").append(i).append("]");
}
return sbParamArrayList.toString();
}
/**
* Creates a parameter array list.
*
* @param params
* @param paramValues
* @return parameter array list
*/
protected String createParamArray(List<Param> params,
List<String> paramValues) {
StringBuilder sbParamArray = new StringBuilder();
boolean firstInit = true;
for (int i = 0; i < params.size() && i < paramValues.size(); i++) {
if (firstInit) {
sbParamArray.append("Object[] paramList = new Object[")
.append(params.size()).append("];");
firstInit = false;
}
sbParamArray
.append("paramList[")
.append(i)
.append("] = ")
.append(JDTUtils.formatValue(paramValues.get(i), params
.get(i).getType())).append(";").append(RETURN);
}
return sbParamArray.toString();
}
/**
* Creates the test base mocks.
*
* @param mocks
* @return test base mocks
*/
protected String createTestBaseMocks(Mocks mocks) {
if (mocks == null)
return "";
StringBuilder sbMockMethods = new StringBuilder();
String resultType;
String resultValue;
String modifier;
for (Method tmlMockMethod : mocks.getMethod()) {
if (tmlMockMethod.getResult() != null) {
resultType = tmlMockMethod.getResult().getType();
resultValue = tmlMockMethod.getResult().getValue();
resultValue = JDTUtils.formatValue(resultValue, resultType);
resultValue = "return " + resultValue + ";";
} else {
resultType = TYPE_VOID;
resultValue = "";
}
modifier = tmlMockMethod.getModifier();
if (MOD_PACKAGE.equals(modifier)) {
modifier = "";
}
sbMockMethods.append(modifier).append(" ").append(resultType)
.append(" ").append(tmlMockMethod.getName()).append("(")
.append(createParamList(tmlMockMethod.getParam()))
.append(") {").append(resultValue).append("}");
}
return sbMockMethods.toString();
}
/**
* Creates the test methods.
*
* @param type
* @param methodMap
* @param methodsToCreate
* @param tmlSettings
* @param baseClassName
* @param monitor
* @param increment
* @return true if the processing was stopped
* @throws JavaModelException
*/
protected boolean createTestMethods(IType type,
HashMap<IMethod, Method> methodMap, List<IMethod> methodsToCreate,
Settings tmlSettings, String baseClassName,
IProgressMonitor monitor, int increment) throws JavaModelException {
int i = 0;
boolean failAssertions = tmlSettings.isFailAssertions();
for (IMethod methodToCreate : methodsToCreate) {
Method tmlMethod = methodMap.get(methodToCreate);
createTestMethod(type, tmlMethod, baseClassName, failAssertions);
if (i++ == increment) {
i = 0;
// increment task
if (incrementTask(monitor))
return true;
}
}
return false;
}
/**
* Creates a test method.
*
* @param type
* @param tmlMethod
* @param baseClassName
* @param failAssertions
* @param hookAfterMethodCall
* @throws JavaModelException
*/
protected void createTestMethod(IType type, Method tmlMethod,
String baseClassName, boolean failAssertions)
throws JavaModelException {
String testMethodNamePrefix = getTestmethodPrefix();
String testMethodNamePostfix = getTestmethodPostfix();
String testMethodName;
String testMethodBody;
// create test-method-name
if (testMethodNamePrefix != null && testMethodNamePrefix.length() > 0) {
testMethodName = testMethodNamePrefix
+ GeneratorUtils.firstCharToUpper(tmlMethod.getName())
+ testMethodNamePostfix;
} else {
testMethodName = tmlMethod.getName() + testMethodNamePostfix;
}
// create test-method-body
testMethodBody = createTestMethodBody(type, tmlMethod, testMethodName,
baseClassName, failAssertions);
// create method ref
String annoMethodRef = GeneratorUtils.createAnnoMethodRef(
tmlMethod.getName(), tmlMethod.getSignature());
JDTUtils.createMethod(type, MOD_PUBLIC, TYPE_VOID, testMethodName,
"Exception", null, testMethodBody, true, annoMethodRef,
ANNO_JUNIT_TEST);
}
/**
* Creates the test method body.
*
* @param type
* @param tmlMethod
* @param methodName
* @param baseClassName
* @param failAssertions
* @param hookAfterMethodCall
* @return the created test method body
* @throws JavaModelException
*/
protected String createTestMethodBody(IType type, Method tmlMethod,
String methodName, String baseClassName, boolean failAssertions)
throws JavaModelException {
StringBuilder sbTestMethodBody = new StringBuilder();
List<Param> params = tmlMethod.getParam();
String testbaseMethodName = "";
String testBaseVariableName = "testSubject"; // GeneratorUtils.firstCharToLower(baseClassName);
// test-base-variable
if (!tmlMethod.isStatic()) {
sbTestMethodBody.append(baseClassName).append(" ")
.append(testBaseVariableName).append(";");
}
// create param initializations
createParamInitializations(params, sbTestMethodBody);
// create result-variable
Result result = tmlMethod.getResult();
String resultVariableName = "";
String resultType = "";
if (result != null) {
resultVariableName = result.getName();
resultType = result.getType();
sbTestMethodBody.append(resultType).append(" ")
.append(resultVariableName).append(";");
}
List<TestCase> testCases = tmlMethod.getTestCase();
boolean isPublic = MOD_PUBLIC.equals(tmlMethod.getModifier());
for (TestCase tmlTestcase : testCases) {
sbTestMethodBody.append(RETURN + RETURN + "// ")
.append(tmlTestcase.getName()).append(RETURN);
testbaseMethodName = createTestBaseMethodName(tmlTestcase
.getTestBase());
createTestCaseBody(sbTestMethodBody, tmlMethod.getName(),
baseClassName, testBaseVariableName, testbaseMethodName,
resultVariableName, resultType, params,
tmlTestcase.getParamAssignments(), isPublic,
tmlMethod.isStatic());
// assertions
createAssertionsMethodBody(sbTestMethodBody, resultVariableName,
resultType, testBaseVariableName, tmlTestcase);
}
// fail-assertion
if (failAssertions) {
sbTestMethodBody.append(RETURN + RETURN).append(FAIL_ASSERTION);
}
return sbTestMethodBody.toString();
}
/**
* Creates the test method body.
*
* @param sbTestMethodBody
* @param methodName
* @param baseClassName
* @param testBaseVariableName
* @param testBaseMethodName
* @param resultVariableName
* @param resultType
* @param params
* @param paramAssignments
* @param isPublic
* @param isStatic
*/
protected void createTestCaseBody(StringBuilder sbTestMethodBody,
String methodName, String baseClassName,
String testBaseVariableName, String testBaseMethodName,
String resultVariableName, String resultType, List<Param> params,
List<ParamAssignment> paramAssignments, boolean isPublic,
boolean isStatic) {
String baseName;
// create test-base
if (!isStatic) {
baseName = testBaseVariableName;
sbTestMethodBody.append(testBaseVariableName).append("=")
.append(testBaseMethodName).append("();");
} else {
baseName = baseClassName;
}
// create param assignments
createParamAssignments(paramAssignments, sbTestMethodBody);
// create param-list
String paramNameList = createParamNameList(params);
// result
if (resultVariableName.length() > 0) {
sbTestMethodBody.append(resultVariableName).append("=");
}
if (isPublic) {
// method-call
sbTestMethodBody.append(baseName).append(".").append(methodName)
.append("(").append(paramNameList).append(");");
} else {
// method-call with white-box-call
if (paramNameList.length() > 0) {
paramNameList = ", new Object[]{" + paramNameList + "}";
}
if (isStatic) {
baseName += ".class";
}
// TODO abfrage ob powermock oder jmockit
// sbTestMethodBody.append("Whitebox.invokeMethod(").append(baseName).append(", ").append(QUOTES)
// .append(methodName).append(QUOTES).append(paramValueList).append(");");
sbTestMethodBody.append("Deencapsulation.invoke(").append(baseName)
.append(", ").append(QUOTES).append(methodName)
.append(QUOTES).append(paramNameList).append(");");
}
}
protected String createParamNameList(List<Param> params) {
StringBuilder sbParamList = new StringBuilder();
String comma = "";
for (Param param : params) {
sbParamList.append(comma);
sbParamList.append(param.getName());
comma = ", ";
}
return sbParamList.toString();
}
protected void createParamInitializations(List<Param> params,
StringBuilder methodBody) {
// variable declaration and default initialization
for (Param param : params) {
methodBody.append(param.getType()).append(" ")
.append(param.getName()).append(" = ")
.append(JDTUtils.createInitValue(param.getType(), true))
.append(";").append(RETURN);
}
}
/**
* Creates the param assignments
*
* @param paramAssignments
* @param methodBody
*/
protected void createParamAssignments(
List<ParamAssignment> paramAssignments, StringBuilder methodBody) {
for (ParamAssignment pa : paramAssignments) {
methodBody.append(pa.getParamName()).append(" = ")
.append(pa.getAssignment()).append(";\n");
}
}
/**
* Creates the method body for the assertions.
*
* @param sbTestMethodBody
* @param resultVariableName
* @param resultType
* @param testBaseVariableName
* @param tmlTestCase
*/
protected void createAssertionsMethodBody(StringBuilder sbTestMethodBody,
String resultVariableName, String resultType,
String testBaseVariableName, TestCase tmlTestCase) {
String baseType;
for (Assertion tmlAssertion : tmlTestCase.getAssertion()) {
// base
String base;
if ("{result}".equals(tmlAssertion.getBase())) {
if ("".equals(resultVariableName)) {
continue;
}
base = "result";
baseType = resultType;
} else {
base = testBaseVariableName + "." + tmlAssertion.getBase()
+ "()";
baseType = tmlAssertion.getBaseType();
}
// assertion-type
AssertionType type = tmlAssertion.getType();
String assertionType = createAssertionType(type, baseType);
// Assertion
sbTestMethodBody.append(RETURN + "Assert.").append(assertionType)
.append("(");
// message
String message = "";
if (tmlAssertion.getMessage() != null
&& tmlAssertion.getMessage().length() > 0) {
message = tmlTestCase.getName() + ": "
+ tmlAssertion.getMessage();
sbTestMethodBody.append(QUOTES).append(message).append(QUOTES)
.append(", ");
}
// actual
if (type == AssertionType.EQUALS
|| type == AssertionType.NOT_EQUALS) {
// test-value
String testValue = tmlAssertion.getValue();
testValue = JDTUtils.formatValue(testValue, baseType);
sbTestMethodBody.append(testValue).append(", ");
// expected
sbTestMethodBody.append(base);
// delta
if (JDTUtils.isNumber(baseType) && !JDTUtils.isArray(baseType)) {
sbTestMethodBody.append(", 0");
}
} else {
// expected
sbTestMethodBody.append(base);
}
sbTestMethodBody.append(");");
}
}
/**
* Returns the assertion as String.
*
* @param type
* @param baseType
* @return assertion as String
*/
protected String createAssertionType(AssertionType type, String baseType) {
String assertionType = "assertEquals";
if (type == AssertionType.EQUALS) {
if (JDTUtils.isArray(baseType)) {
assertionType = "assertArrayEquals";
} else {
assertionType = "assertEquals";
}
} else if (type == AssertionType.NOT_EQUALS) {
assertionType = "assertNotEquals";
} else if (type == AssertionType.IS_NULL) {
assertionType = "assertNull";
} else if (type == AssertionType.NOT_NULL) {
assertionType = "assertNotNull";
} else if (type == AssertionType.IS_TRUE) {
assertionType = "assertTrue";
} else if (type == AssertionType.IS_FALSE) {
assertionType = "assertFalse";
}
return assertionType;
}
/**
* Creates a parameter list.
*
* @param params
* @return the created parameter list
*/
protected String createParamList(List<Param> params) {
Param tmlParam;
StringBuilder sbParamList = new StringBuilder();
boolean firstInit = true;
for (int i = 0; i < params.size(); i++) {
if (!firstInit)
sbParamList.append(", ");
else
firstInit = false;
tmlParam = params.get(i);
sbParamList.append(tmlParam.getType()).append(" ")
.append(tmlParam.getName());
}
return sbParamList.toString();
}
/**
* Creates a parameter list with values.
*
* @param params
* @param paramValues
* @return the created parameter list with values
*/
protected String createParamValueList(List<Param> params,
List<String> paramValues) {
StringBuilder sbParamList = new StringBuilder();
boolean firstInit = true;
Param tmlParam;
String value, type;
for (int i = 0; i < params.size()
&& (paramValues == null || i < paramValues.size()); i++) {
if (!firstInit)
sbParamList.append(", ");
else
firstInit = false;
tmlParam = params.get(i);
type = tmlParam.getType();
if (paramValues != null) {
value = paramValues.get(i);
} else {
value = "";
}
value = JDTUtils.formatValue(value, type);
sbParamList.append(value);
}
return sbParamList.toString();
}
protected String getTestmethodPrefix() {
if (testmethodPrefix == null)
testmethodPrefix = JUTPreferences.getTestMethodPrefix();
return testmethodPrefix;
}
/**
* @return the test method post fix
*/
protected String getTestmethodPostfix() {
if (testmethodPostfix == null)
testmethodPostfix = JUTPreferences.getTestMethodPostfix();
return testmethodPostfix;
}
/**
* Creates the annotation test priority.
*
* @return the created annotations
*/
protected String createAnnoTestprio(Testprio testprio) {
if (testprio == Testprio.DEFAULT)
return ANNO_TESTPRIO + RETURN;
return ANNO_TESTPRIO
+ "(prio=org.junit.tools.generator.model.tml.Testprio."
+ testprio + ")" + RETURN;
}
/**
* Returns if the annotation generated is set.
*
* @param annotations
* @return true if the annotation for the generated hooks is set.
*/
protected boolean isGenerated(IAnnotation[] annotations) {
for (IAnnotation annotation : annotations) {
if (ANNO_GENERATED_NAME.equals(annotation.getElementName()))
return true;
}
return false;
}
}
|
Change-Id: I3dfc5db1558d164f1e89d5f3c7b35f2b58038ad7
| org.junit.tools/src/org/junit/tools/generator/TestClassGenerator.java | <ide><path>rg.junit.tools/src/org/junit/tools/generator/TestClassGenerator.java
<ide> @SuppressWarnings("restriction")
<ide> // TODO avoid restrictions
<ide> public class TestClassGenerator implements ITestClassGenerator,
<del> IGeneratorConstants {
<del>
<del> protected String annoGenerated = null;
<del>
<del> protected String testmethodPrefix;
<del>
<del> protected String testmethodPostfix;
<del>
<del> protected boolean defaultTestbaseMethodCreated = false;
<del>
<del> @Override
<del> public ICompilationUnit generate(GeneratorModel model,
<del> List<ITestDataFactory> testDataFactories, IProgressMonitor monitor)
<del> throws Exception {
<del> boolean writeTML = JUTPreferences.isWriteTML();
<del>
<del> defaultTestbaseMethodCreated = false;
<del>
<del> Test tmlTest = model.getTmlTest();
<del> Settings tmlSettings = tmlTest.getSettings();
<del>
<del> JUTClassesAndPackages utmClassesAndPackages = model.getJUTElements()
<del> .getClassesAndPackages();
<del> ICompilationUnit testClass = utmClassesAndPackages.getTestClass(true);
<del> String testClassName = utmClassesAndPackages.getTestClassName();
<del> ICompilationUnit baseClass = utmClassesAndPackages.getBaseClass();
<del> String baseClassName = utmClassesAndPackages.getBaseClassName();
<del> IType type;
<del>
<del> // begin task
<del> int methodSize = tmlTest.getMethod().size();
<del> int increment;
<del>
<del> if (methodSize >= 300) {
<del> increment = 50;
<del> } else if (methodSize >= 100) {
<del> increment = 30;
<del> } else {
<del> increment = 20;
<del> }
<del>
<del> methodSize = methodSize / increment;
<del>
<del> monitor.beginTask("", 6 + methodSize);
<del>
<del> // create or update test-class-frame
<del> type = createTestClassFrame(testClass, tmlTest, testClassName);
<del>
<del> // increment task
<del> if (incrementTask(monitor))
<del> return null;
<del>
<del> // delete generated elements
<del> if (testClass.exists()) {
<del> deleteGeneratedElements(testClass, tmlSettings);
<del> }
<del>
<del> // increment task
<del> if (incrementTask(monitor))
<del> return null;
<del>
<del> // create standard-imports
<del> createStandardImports(testClass, tmlTest);
<del>
<del> // increment task
<del> if (incrementTask(monitor))
<del> return null;
<del>
<del> // create standard-class-fields
<del> createStandardClassFields(type, tmlTest, testClassName);
<del>
<del> // increment task
<del> if (incrementTask(monitor))
<del> return null;
<del>
<del> // create standard-methods
<del> createStandardMethods(type, tmlSettings);
<del>
<del> // increment task
<del> if (incrementTask(monitor))
<del> return null;
<del>
<del> // create test-base-methods
<del> if (writeTML) {
<del> createTestBaseMethods(type, tmlTest, baseClassName);
<del> } else {
<del> createTestBaseMethods(type, baseClass, baseClassName, model
<del> .getJUTElements().getConstructorsAndMethods()
<del> .getBaseClassConstructors(), testDataFactories);
<del> }
<del>
<del> // increment task
<del> if (incrementTask(monitor))
<del> return null;
<del>
<del> // delete test-methods
<del> for (IMethod methodToDelete : model.getMethodsToDelete()) {
<del> methodToDelete.delete(true, null);
<del> }
<del>
<del> // create test-methods
<del> if (createTestMethods(type, model.getMethodMap(),
<del> model.getMethodsToCreate(), tmlSettings, baseClassName,
<del> monitor, increment)) {
<del> return null;
<del> }
<del>
<del> // update test-methods (method-ref)
<del> updateExistingMethods(type.getCompilationUnit(), type,
<del> model.getExistingMethods());
<del>
<del> IPackageFragment testPackage = model.getJUTElements()
<del> .getClassesAndPackages().getTestPackage();
<del> testClass.createPackageDeclaration(testPackage.getElementName(), null);
<del>
<del> // create static standard-imports
<del> createStandardStaticImports(testClass);
<del>
<del> // save test-class
<del> testClass.save(null, true);
<del> testClass.makeConsistent(null);
<del> if (testClass.hasUnsavedChanges()) {
<del> testClass.commitWorkingCopy(true, null);
<del> }
<del>
<del> return testClass;
<del> }
<del>
<del> @SuppressWarnings("unchecked")
<del> protected void updateExistingMethods(ICompilationUnit cu, IType cuType,
<del> HashMap<MethodRef, IMethod> existingMethods)
<del> throws JavaModelException, IllegalArgumentException,
<del> MalformedTreeException, BadLocationException {
<del> MethodRef methodRef;
<del> Annotation annotation;
<del>
<del> for (Entry<MethodRef, IMethod> entry : existingMethods.entrySet()) {
<del> // update method reference
<del> methodRef = entry.getKey();
<del> if (methodRef.isSignatureChanged()) {
<del> // delete old annotation
<del> for (IAnnotation iAnnotation : entry.getValue()
<del> .getAnnotations()) {
<del> if (iAnnotation instanceof Annotation) {
<del> annotation = (Annotation) iAnnotation;
<del>
<del> if (ANNO_METHOD_REF_NAME.equals(iAnnotation
<del> .getElementName())) {
<del> if (annotation.exists()) {
<del> annotation.delete(true, null);
<del> }
<del> }
<del>
<del> }
<del> }
<del>
<del> // create new annotation
<del> CompilationUnit astRoot = JDTUtils.createASTRoot(cu);
<del> MethodDeclaration md = JDTUtils.createMethodDeclaration(
<del> astRoot, entry.getValue());
<del>
<del> final ASTRewrite rewriter = ASTRewrite.create(md.getAST());
<del>
<del> NormalAnnotation newNormalAnnotation = rewriter.getAST()
<del> .newNormalAnnotation();
<del>
<del> newNormalAnnotation.setTypeName(astRoot.getAST().newName(
<del> "MethodRef"));
<del>
<del> newNormalAnnotation.values().add(
<del> createAnnotationMemberValuePair(astRoot.getAST(),
<del> "name", methodRef.getName()));
<del> newNormalAnnotation.values().add(
<del> createAnnotationMemberValuePair(astRoot.getAST(),
<del> "signature", methodRef.getSignatureNew()));
<del>
<del> rewriter.getListRewrite(md,
<del> MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(
<del> newNormalAnnotation, null);
<del>
<del> // apply changes
<del> TextEdit textEdit = rewriter.rewriteAST();
<del> Document document = new Document(cu.getSource());
<del> textEdit.apply(document);
<del> String newSource = document.get();
<del> // update of the compilation unit
<del> cu.getBuffer().setContents(newSource);
<del> }
<del> }
<del>
<del> }
<del>
<del> protected MemberValuePair createAnnotationMemberValuePair(final AST ast,
<del> final String name, final String value) {
<del>
<del> final MemberValuePair mvp = ast.newMemberValuePair();
<del> mvp.setName(ast.newSimpleName(name));
<del> StringLiteral stringLiteral = ast.newStringLiteral();
<del> stringLiteral.setLiteralValue(value);
<del> mvp.setValue(stringLiteral);
<del> return mvp;
<del> }
<del>
<del> protected void createTestBaseMethods(IType type,
<del> ICompilationUnit baseClass, String baseClassName,
<del> Vector<IMethod> constructors,
<del> List<ITestDataFactory> testDataFactories) throws JavaModelException {
<del> String testBaseMethodBody;
<del> StringBuilder classCreationChain;
<del> classCreationChain = new StringBuilder();
<del>
<del> String testBaseMethodName = "createTestSubject";
<del> if (type.getMethod(testBaseMethodName, null).exists()) {
<del> return;
<del> }
<del>
<del> JDTUtils.createClassCreationChain(baseClass.findPrimaryType(),
<del> classCreationChain, testDataFactories);
<del> testBaseMethodBody = " return " + classCreationChain.toString() + ";";
<del>
<del> JDTUtils.createMethod(type, MOD_PRIVATE, baseClassName,
<del> testBaseMethodName, null, null, testBaseMethodBody, false);
<del> }
<del>
<del> /**
<del> * Creates test base methods.
<del> *
<del> * @param type
<del> * @param tmlTest
<del> * @param testBaseName
<del> * @throws JavaModelException
<del> */
<del> protected void createTestBaseMethods(IType type, Test tmlTest,
<del> String testBaseName) throws JavaModelException {
<del> Settings tmlSettings = tmlTest.getSettings();
<del> TestBases tmlTestbases = tmlTest.getTestBases();
<del> if (tmlSettings == null || tmlTestbases == null) {
<del> return;
<del> }
<del>
<del> String testBaseMethodBody;
<del> String testBaseMethodName;
<del>
<del> for (Constructor tmlConstructor : tmlTestbases.getConstructor()) {
<del>
<del> for (TestBase tmlTestbase : tmlConstructor.getTestBase()) {
<del> testBaseMethodName = createTestBaseMethodName(tmlTestbase
<del> .getName());
<del>
<del> testBaseMethodBody = createTestBaseMethodBody(tmlTestbase,
<del> testBaseName, testBaseMethodName,
<del> tmlConstructor.getParam(), tmlSettings);
<del>
<del> JDTUtils.createMethod(type, MOD_PRIVATE, testBaseName,
<del> testBaseMethodName, "Exception", null,
<del> testBaseMethodBody, false);
<del> }
<del>
<del> if (tmlConstructor.getTestBase().size() == 0) {
<del> createTestBaseMethodDefault(type, testBaseName,
<del> tmlConstructor.getParam());
<del> }
<del> }
<del> }
<del>
<del> /**
<del> * Creates the standard methods.
<del> *
<del> * @param type
<del> * @param tmlSettings
<del> * @throws JavaModelException
<del> */
<del> protected void createStandardMethods(IType type, Settings tmlSettings)
<del> throws JavaModelException {
<del> if (tmlSettings == null) {
<del> return;
<del> }
<del>
<del> if (tmlSettings.isSetUp()) {
<del> JDTUtils.createMethod(type, MOD_PUBLIC, TYPE_VOID,
<del> STANDARD_METHOD_BEFORE, EXCEPTION, null, "", false,
<del> ANNO_JUNIT_BEFORE);
<del> }
<del>
<del> if (tmlSettings.isSetUpBeforeClass()) {
<del> JDTUtils.createMethod(type, MOD_PUBLIC + MOD_STATIC_WITH_BLANK,
<del> TYPE_VOID, STANDARD_METHOD_BEFORE_ClASS, EXCEPTION, null,
<del> "", false, ANNO_JUNIT_BEFORE_CLASS);
<del> }
<del>
<del> if (tmlSettings.isTearDown()) {
<del> JDTUtils.createMethod(type, MOD_PUBLIC, TYPE_VOID,
<del> STANDARD_METHOD_AFTER, EXCEPTION, null, "", false,
<del> ANNO_JUNIT_AFTER);
<del> }
<del>
<del> if (tmlSettings.isTearDownBeforeClass()) {
<del> JDTUtils.createMethod(type, MOD_PUBLIC + MOD_STATIC_WITH_BLANK,
<del> TYPE_VOID, STANDARD_METHOD_AFTER_CLASS, "Exception", null,
<del> "", false, ANNO_JUNIT_AFTER_CLASS);
<del> }
<del> }
<del>
<del> /**
<del> * Create a hook after a method call.
<del> *
<del> * @param type
<del> * @param hookMethodName
<del> * @param param
<del> * @throws JavaModelException
<del> */
<del> protected void createHookAfterMethodCall(IType type, String hookMethodName,
<del> String param) throws JavaModelException {
<del> JDTUtils.createMethod(type, MOD_PRIVATE, TYPE_VOID, hookMethodName,
<del> "Exception", param, "", false);
<del> }
<del>
<del> /**
<del> * Increments the task.
<del> *
<del> * @param monitor
<del> * @return true if not canceled
<del> */
<del> protected boolean incrementTask(IProgressMonitor monitor) {
<del> return incrementTask(monitor, 1);
<del> }
<del>
<del> /**
<del> * Increments the task.
<del> *
<del> * @param monitor
<del> * @param i
<del> * @return true if not canceled
<del> */
<del> protected boolean incrementTask(IProgressMonitor monitor, int i) {
<del> if (monitor.isCanceled())
<del> return true;
<del> monitor.worked(i);
<del> return false;
<del> }
<del>
<del> /**
<del> * Deletes the generated elements.
<del> *
<del> * @param testClass
<del> * @param tmlSettings
<del> * @throws JavaModelException
<del> */
<del> protected void deleteGeneratedElements(ICompilationUnit testClass,
<del> Settings tmlSettings) throws JavaModelException {
<del> IType[] types = testClass.getTypes();
<del> IMethod method;
<del> IField field;
<del>
<del> for (IType type : types) {
<del> for (IJavaElement element : type.getChildren()) {
<del> if (element instanceof IMethod) {
<del> method = (IMethod) element;
<del>
<del> if (!deleteStandardMethod(
<del> method.getElementName().replace(".java", ""),
<del> tmlSettings)) {
<del> continue;
<del> }
<del> } else if (element instanceof IField) {
<del> field = (IField) element;
<del> if (isGenerated(field.getAnnotations())) {
<del> field.delete(true, null);
<del> }
<del> }
<del> }
<del> }
<del> }
<del>
<del> /**
<del> * @param tmlSettings
<del> * @return isStandardMethod
<del> */
<del> protected boolean deleteStandardMethod(String methodName,
<del> Settings tmlSettings) {
<del> if (STANDARD_METHOD_BEFORE.equals(methodName)) {
<del> if (!tmlSettings.isSetUp()) {
<del> return true;
<del> } else {
<del> return false;
<del> }
<del> } else if (STANDARD_METHOD_BEFORE_ClASS.equals(methodName)) {
<del> if (!tmlSettings.isSetUpBeforeClass()) {
<del> return true;
<del> } else {
<del> return false;
<del> }
<del> } else if (STANDARD_METHOD_AFTER.equals(methodName)) {
<del> if (!tmlSettings.isTearDown()) {
<del> return true;
<del> } else {
<del> return false;
<del> }
<del> } else if (STANDARD_METHOD_AFTER_CLASS.equals(methodName)) {
<del> if (!tmlSettings.isTearDownBeforeClass()) {
<del> return true;
<del> } else {
<del> return false;
<del> }
<del> }
<del> return true;
<del> }
<del>
<del> /**
<del> * Creates the test class frame.
<del> *
<del> * @param testCompilationUnit
<del> * @param tmlTest
<del> * @param testClassName
<del> * @return the created test class frame
<del> * @throws JavaModelException
<del> */
<del> protected IType createTestClassFrame(ICompilationUnit testCompilationUnit,
<del> Test tmlTest, String testClassName) throws JavaModelException {
<del> IType type = testCompilationUnit.getType(testClassName);
<del>
<del> if (!type.exists()) {
<del> return createTestClassFrame(testCompilationUnit, tmlTest,
<del> testClassName, null);
<del> } else {
<del> // check if recreation of test-class-frame is necessary
<del> Vector<Annotation> annotationsToDelete = getAnnotationsToDelete(
<del> type, tmlTest);
<del>
<del> if (annotationsToDelete != null) {
<del> for (Annotation annotation : annotationsToDelete)
<del> annotation.delete(true, null);
<del>
<del> String source = type.getSource();
<del> type.delete(true, null);
<del> return createTestClassFrame(testCompilationUnit, tmlTest,
<del> testClassName, source);
<del> }
<del> }
<del>
<del> return type;
<del> }
<del>
<del> /**
<del> * Returns the annotation to delete.
<del> *
<del> * @param type
<del> * @param tmlTest
<del> * @throws JavaModelException
<del> */
<del> protected Vector<Annotation> getAnnotationsToDelete(IType type, Test tmlTest)
<del> throws JavaModelException {
<del> Vector<Annotation> annotationsToDelete = new Vector<Annotation>();
<del> Annotation annotation;
<del> boolean recreationNecessary = false;
<del>
<del> for (IAnnotation iAnnotation : type.getAnnotations()) {
<del> if (iAnnotation instanceof Annotation) {
<del> annotation = (Annotation) iAnnotation;
<del>
<del> if (ANNO_GENERATED_NAME.equals(iAnnotation.getElementName())) {
<del> annotationsToDelete.add(annotation);
<del> IMemberValuePair[] memberValuePairs = annotation
<del> .getMemberValuePairs();
<del> for (IMemberValuePair valuePair : memberValuePairs) {
<del> if (!VERSION.equals(valuePair.getValue())) {
<del> recreationNecessary = true;
<del> break;
<del> }
<del> }
<del> } else if (ANNO_TESTPRIO_NAME.equals(iAnnotation
<del> .getElementName())) {
<del> annotationsToDelete.add(annotation);
<del> IMemberValuePair[] memberValuePairs = annotation
<del> .getMemberValuePairs();
<del>
<del> if (memberValuePairs.length == 0) {
<del> if (tmlTest.getTestPrio().compareTo(Testprio.DEFAULT) != 0)
<del> recreationNecessary = true;
<del> }
<del>
<del> for (IMemberValuePair valuePair : memberValuePairs) {
<del> if (!valuePair.getValue().toString()
<del> .endsWith(tmlTest.getTestPrio().toString())) {
<del> recreationNecessary = true;
<del> break;
<del> }
<del> }
<del> }
<del> }
<del> }
<del>
<del> if (!recreationNecessary)
<del> return null;
<del>
<del> return annotationsToDelete;
<del> }
<del>
<del> /**
<del> * Creates a test class frame.
<del> *
<del> * @param testCompilationUnit
<del> * @param tmlTest
<del> * @param testclassName
<del> * @param source
<del> * @return the created test class frame
<del> * @throws JavaModelException
<del> */
<del> protected IType createTestClassFrame(ICompilationUnit testCompilationUnit,
<del> Test tmlTest, String testclassName, String source)
<del> throws JavaModelException {
<del> // create annotations
<del> String annotations = createTestClassFrameAnnotations(tmlTest
<del> .getTestPrio());
<del>
<del> // create type
<del> String superType = "";
<del>
<del> if (source == null) {
<del> String customComment = getTestClassComment();
<del>
<del> superType = tmlTest.getSuperClass();
<del>
<del> String extendsStmt = "";
<del> if (!(superType == null || "".equals(superType))) {
<del> extendsStmt = " extends " + superType;
<del> } else {
<del> superType = "";
<del> }
<del>
<del> source = customComment + annotations.toString() + MOD_PUBLIC
<del> + " class " + testclassName + extendsStmt + "{ " + RETURN
<del> + "}";
<del> } else {
<del> source = annotations + source;
<del> }
<del>
<del> IType type = testCompilationUnit.createType(source, null, true, null);
<del>
<del> String superTypePackage = tmlTest.getSuperClassPackage();
<del> if (!"".equals(superType) && superTypePackage != null
<del> && !"".equals(superTypePackage)) {
<del> testCompilationUnit.createImport(
<del> superTypePackage + "." + superType, null, null);
<del> }
<del>
<del> return type;
<del> }
<del>
<del> protected String getTestClassComment() {
<del> return "";
<del> }
<del>
<del> /**
<del> * Creates the test class annotations.
<del> *
<del> * @param testprio
<del> * @return the created annotations
<del> */
<del> protected String createTestClassFrameAnnotations(Testprio testprio) {
<del> // create annotations
<del> StringBuilder annotations = new StringBuilder();
<del>
<del> // create generator-annotation
<del> annotations.append(createAnnoGenerated());
<del>
<del> // test-priority-annotation
<del> annotations.append(createAnnoTestprio(testprio));
<del>
<del> return annotations.toString();
<del> }
<del>
<del> /**
<del> * Creates the annotation generated.
<del> *
<del> * @return the created annotation
<del> */
<del> protected String createAnnoGenerated() {
<del> if (annoGenerated == null) {
<del> annoGenerated = GeneratorUtils.createAnnoGenerated();
<del> }
<del> return annoGenerated;
<del> }
<del>
<del> /**
<del> * Creates the standard imports.
<del> *
<del> * @param compilationUnit
<del> * @param tmlTest
<del> * @throws JavaModelException
<del> */
<del> protected void createStandardImports(ICompilationUnit compilationUnit,
<del> Test tmlTest) throws JavaModelException {
<del>
<del> compilationUnit.createImport("java.util.*", null, null);
<del> compilationUnit.createImport("org.junit.Assert", null, null);
<del> compilationUnit.createImport("org.junit.Test", null, null);
<del>
<del> if (tmlTest.getSettings().isLogger()) {
<del> compilationUnit
<del> .createImport("java.util.logging.Logger", null, null);
<del> }
<del> }
<del>
<del> protected void createStandardStaticImports(ICompilationUnit compilationUnit)
<del> throws JavaModelException {
<del> IJavaElement importAbove = null;
<del> IImportDeclaration[] imports = compilationUnit.getImports();
<del> if (imports.length > 0) {
<del> importAbove = imports[0];
<del> compilationUnit.createImport("org.junit.Assert.*", importAbove,
<del> Flags.AccStatic, null);
<del> }
<del> }
<del>
<del> /**
<del> * Create standard class fields.
<del> *
<del> * @param type
<del> * @param tmlTest
<del> * @param testclassName
<del> * @throws JavaModelException
<del> */
<del> protected void createStandardClassFields(IType type, Test tmlTest,
<del> String testclassName) throws JavaModelException {
<del> if (tmlTest.getSettings().isLogger()) {
<del> String logger = createAnnoGenerated() + " " + MOD_PRIVATE
<del> + " Logger logger = Logger.getLogger(" + testclassName
<del> + ".class.toString());";
<del> type.createField(logger, null, false, null);
<del> }
<del> }
<del>
<del> /**
<del> * Creates the test base method with default values.
<del> *
<del> * @param type
<del> * @param testbaseName
<del> * @param params
<del> * @throws JavaModelException
<del> */
<del> protected void createTestBaseMethodDefault(IType type, String testbaseName,
<del> List<Param> params) throws JavaModelException {
<del> if (defaultTestbaseMethodCreated)
<del> return;
<del>
<del> String paramValueList;
<del> if (params != null) {
<del> paramValueList = createParamValueList(params, null);
<del> } else {
<del> paramValueList = "";
<del> }
<del>
<del> StringBuilder sbMethodBody = new StringBuilder();
<del> sbMethodBody.append("return new ").append(testbaseName).append("(")
<del> .append(paramValueList).append(");");
<del>
<del> JDTUtils.createMethod(type, MOD_PRIVATE, testbaseName,
<del> TESTSUBJECT_METHOD_PREFIX, null, null, sbMethodBody.toString());
<del>
<del> defaultTestbaseMethodCreated = true;
<del> }
<del>
<del> /**
<del> * Creates the test base method name.
<del> *
<del> * @param tmlTestBaseName
<del> * @return test base method name
<del> */
<del> protected String createTestBaseMethodName(String tmlTestBaseName) {
<del> String testBaseName = GeneratorUtils.firstCharToUpper(tmlTestBaseName);
<del> String testBaseMethodName = TESTSUBJECT_METHOD_PREFIX + testBaseName;
<del> return testBaseMethodName;
<del> }
<del>
<del> /**
<del> * Creates the test base method body.
<del> *
<del> * @param tmlTestbase
<del> * @param testBaseName
<del> * @param testBaseMethodName
<del> * @param params
<del> * @param tmlSettings
<del> * @return the created test base method body
<del> */
<del> protected String createTestBaseMethodBody(TestBase tmlTestbase,
<del> String testBaseName, String testBaseMethodName, List<Param> params,
<del> Settings tmlSettings) {
<del>
<del> StringBuilder sbMethodBody = new StringBuilder();
<del>
<del> String constructorParams = "";
<del> if (params.size() > 0) {
<del> constructorParams = createParamValueList(params,
<del> tmlTestbase.getParamValue());
<del> }
<del>
<del> String testBaseMocks = createTestBaseMocks(tmlTestbase.getMocks());
<del> String testBaseVariableName = GeneratorUtils
<del> .firstCharToLower(testBaseName);
<del>
<del> // test-base initialization
<del> sbMethodBody.append(testBaseName).append(" ")
<del> .append(testBaseVariableName).append("=").append("new ")
<del> .append(testBaseName).append("(").append(constructorParams)
<del> .append(") {").append(testBaseMocks).append("};")
<del> .append(RETURN);
<del>
<del> // return
<del> sbMethodBody.append("return ").append(testBaseVariableName).append(";");
<del>
<del> return sbMethodBody.toString();
<del> }
<del>
<del> /**
<del> * Creates a parameter array list.
<del> *
<del> * @param params
<del> * @return parameter array list
<del> */
<del> protected String createParamArrayList(List<Param> params) {
<del> StringBuilder sbParamArrayList = new StringBuilder();
<del>
<del> boolean firstInit = true;
<del>
<del> for (int i = 0; i < params.size(); i++) {
<del> if (!firstInit) {
<del> sbParamArrayList.append(",");
<del> } else {
<del> firstInit = false;
<del> }
<del>
<del> sbParamArrayList.append("(").append(params.get(i).getType())
<del> .append(")paramList[").append(i).append("]");
<del> }
<del>
<del> return sbParamArrayList.toString();
<del> }
<del>
<del> /**
<del> * Creates a parameter array list.
<del> *
<del> * @param params
<del> * @param paramValues
<del> * @return parameter array list
<del> */
<del> protected String createParamArray(List<Param> params,
<del> List<String> paramValues) {
<del> StringBuilder sbParamArray = new StringBuilder();
<del>
<del> boolean firstInit = true;
<del>
<del> for (int i = 0; i < params.size() && i < paramValues.size(); i++) {
<del> if (firstInit) {
<del> sbParamArray.append("Object[] paramList = new Object[")
<del> .append(params.size()).append("];");
<del> firstInit = false;
<del> }
<del> sbParamArray
<del> .append("paramList[")
<del> .append(i)
<del> .append("] = ")
<del> .append(JDTUtils.formatValue(paramValues.get(i), params
<del> .get(i).getType())).append(";").append(RETURN);
<del> }
<del>
<del> return sbParamArray.toString();
<del> }
<del>
<del> /**
<del> * Creates the test base mocks.
<del> *
<del> * @param mocks
<del> * @return test base mocks
<del> */
<del> protected String createTestBaseMocks(Mocks mocks) {
<del> if (mocks == null)
<del> return "";
<del>
<del> StringBuilder sbMockMethods = new StringBuilder();
<del> String resultType;
<del> String resultValue;
<del> String modifier;
<del>
<del> for (Method tmlMockMethod : mocks.getMethod()) {
<del> if (tmlMockMethod.getResult() != null) {
<del> resultType = tmlMockMethod.getResult().getType();
<del> resultValue = tmlMockMethod.getResult().getValue();
<del> resultValue = JDTUtils.formatValue(resultValue, resultType);
<del> resultValue = "return " + resultValue + ";";
<del> } else {
<del> resultType = TYPE_VOID;
<del> resultValue = "";
<del> }
<del>
<del> modifier = tmlMockMethod.getModifier();
<del> if (MOD_PACKAGE.equals(modifier)) {
<del> modifier = "";
<del> }
<del>
<del> sbMockMethods.append(modifier).append(" ").append(resultType)
<del> .append(" ").append(tmlMockMethod.getName()).append("(")
<del> .append(createParamList(tmlMockMethod.getParam()))
<del> .append(") {").append(resultValue).append("}");
<del> }
<del>
<del> return sbMockMethods.toString();
<del> }
<del>
<del> /**
<del> * Creates the test methods.
<del> *
<del> * @param type
<del> * @param methodMap
<del> * @param methodsToCreate
<del> * @param tmlSettings
<del> * @param baseClassName
<del> * @param monitor
<del> * @param increment
<del> * @return true if the processing was stopped
<del> * @throws JavaModelException
<del> */
<del> protected boolean createTestMethods(IType type,
<del> HashMap<IMethod, Method> methodMap, List<IMethod> methodsToCreate,
<del> Settings tmlSettings, String baseClassName,
<del> IProgressMonitor monitor, int increment) throws JavaModelException {
<del>
<del> int i = 0;
<del>
<del> boolean failAssertions = tmlSettings.isFailAssertions();
<del>
<del> for (IMethod methodToCreate : methodsToCreate) {
<del> Method tmlMethod = methodMap.get(methodToCreate);
<del> createTestMethod(type, tmlMethod, baseClassName, failAssertions);
<del>
<del> if (i++ == increment) {
<del> i = 0;
<add> IGeneratorConstants {
<add>
<add> protected String annoGenerated = null;
<add>
<add> protected String testmethodPrefix;
<add>
<add> protected String testmethodPostfix;
<add>
<add> protected boolean defaultTestbaseMethodCreated = false;
<add>
<add> @Override
<add> public ICompilationUnit generate(GeneratorModel model,
<add> List<ITestDataFactory> testDataFactories, IProgressMonitor monitor)
<add> throws Exception {
<add> boolean writeTML = JUTPreferences.isWriteTML();
<add>
<add> defaultTestbaseMethodCreated = false;
<add>
<add> Test tmlTest = model.getTmlTest();
<add> Settings tmlSettings = tmlTest.getSettings();
<add>
<add> JUTClassesAndPackages utmClassesAndPackages = model.getJUTElements()
<add> .getClassesAndPackages();
<add> ICompilationUnit testClass = utmClassesAndPackages.getTestClass(true);
<add> String testClassName = utmClassesAndPackages.getTestClassName();
<add> ICompilationUnit baseClass = utmClassesAndPackages.getBaseClass();
<add> String baseClassName = utmClassesAndPackages.getBaseClassName();
<add> IType type;
<add>
<add> // begin task
<add> int methodSize = tmlTest.getMethod().size();
<add> int increment;
<add>
<add> if (methodSize >= 300) {
<add> increment = 50;
<add> } else if (methodSize >= 100) {
<add> increment = 30;
<add> } else {
<add> increment = 20;
<add> }
<add>
<add> methodSize = methodSize / increment;
<add>
<add> monitor.beginTask("", 6 + methodSize);
<add>
<add> // create or update test-class-frame
<add> type = createTestClassFrame(testClass, tmlTest, testClassName);
<add>
<ide> // increment task
<ide> if (incrementTask(monitor))
<del> return true;
<del> }
<del> }
<del>
<del> return false;
<del> }
<del>
<del> /**
<del> * Creates a test method.
<del> *
<del> * @param type
<del> * @param tmlMethod
<del> * @param baseClassName
<del> * @param failAssertions
<del> * @param hookAfterMethodCall
<del> * @throws JavaModelException
<del> */
<del> protected void createTestMethod(IType type, Method tmlMethod,
<del> String baseClassName, boolean failAssertions)
<del> throws JavaModelException {
<del> String testMethodNamePrefix = getTestmethodPrefix();
<del> String testMethodNamePostfix = getTestmethodPostfix();
<del> String testMethodName;
<del> String testMethodBody;
<del>
<del> // create test-method-name
<del> if (testMethodNamePrefix != null && testMethodNamePrefix.length() > 0) {
<del> testMethodName = testMethodNamePrefix
<del> + GeneratorUtils.firstCharToUpper(tmlMethod.getName())
<del> + testMethodNamePostfix;
<del> } else {
<del> testMethodName = tmlMethod.getName() + testMethodNamePostfix;
<del> }
<del>
<del> // create test-method-body
<del> testMethodBody = createTestMethodBody(type, tmlMethod, testMethodName,
<del> baseClassName, failAssertions);
<del>
<del> // create method ref
<del> String annoMethodRef = GeneratorUtils.createAnnoMethodRef(
<del> tmlMethod.getName(), tmlMethod.getSignature());
<del>
<del> JDTUtils.createMethod(type, MOD_PUBLIC, TYPE_VOID, testMethodName,
<del> "Exception", null, testMethodBody, true, annoMethodRef,
<del> ANNO_JUNIT_TEST);
<del> }
<del>
<del> /**
<del> * Creates the test method body.
<del> *
<del> * @param type
<del> * @param tmlMethod
<del> * @param methodName
<del> * @param baseClassName
<del> * @param failAssertions
<del> * @param hookAfterMethodCall
<del> * @return the created test method body
<del> * @throws JavaModelException
<del> */
<del> protected String createTestMethodBody(IType type, Method tmlMethod,
<del> String methodName, String baseClassName, boolean failAssertions)
<del> throws JavaModelException {
<del> StringBuilder sbTestMethodBody = new StringBuilder();
<del> List<Param> params = tmlMethod.getParam();
<del> String testbaseMethodName = "";
<del> String testBaseVariableName = "testSubject"; // GeneratorUtils.firstCharToLower(baseClassName);
<del>
<del> // test-base-variable
<del> if (!tmlMethod.isStatic()) {
<del> sbTestMethodBody.append(baseClassName).append(" ")
<del> .append(testBaseVariableName).append(";");
<del> }
<del>
<del> // create param initializations
<del> createParamInitializations(params, sbTestMethodBody);
<del>
<del> // create result-variable
<del> Result result = tmlMethod.getResult();
<del> String resultVariableName = "";
<del> String resultType = "";
<del> if (result != null) {
<del> resultVariableName = result.getName();
<del> resultType = result.getType();
<del>
<del> sbTestMethodBody.append(resultType).append(" ")
<del> .append(resultVariableName).append(";");
<del> }
<del>
<del> List<TestCase> testCases = tmlMethod.getTestCase();
<del> boolean isPublic = MOD_PUBLIC.equals(tmlMethod.getModifier());
<del>
<del> for (TestCase tmlTestcase : testCases) {
<del> sbTestMethodBody.append(RETURN + RETURN + "// ")
<del> .append(tmlTestcase.getName()).append(RETURN);
<del>
<del> testbaseMethodName = createTestBaseMethodName(tmlTestcase
<del> .getTestBase());
<del>
<del> createTestCaseBody(sbTestMethodBody, tmlMethod.getName(),
<del> baseClassName, testBaseVariableName, testbaseMethodName,
<del> resultVariableName, resultType, params,
<del> tmlTestcase.getParamAssignments(), isPublic,
<del> tmlMethod.isStatic());
<del>
<del> // assertions
<del> createAssertionsMethodBody(sbTestMethodBody, resultVariableName,
<del> resultType, testBaseVariableName, tmlTestcase);
<del> }
<del>
<del> // fail-assertion
<del> if (failAssertions) {
<del> sbTestMethodBody.append(RETURN + RETURN).append(FAIL_ASSERTION);
<del> }
<del>
<del> return sbTestMethodBody.toString();
<del> }
<del>
<del> /**
<del> * Creates the test method body.
<del> *
<del> * @param sbTestMethodBody
<del> * @param methodName
<del> * @param baseClassName
<del> * @param testBaseVariableName
<del> * @param testBaseMethodName
<del> * @param resultVariableName
<del> * @param resultType
<del> * @param params
<del> * @param paramAssignments
<del> * @param isPublic
<del> * @param isStatic
<del> */
<del> protected void createTestCaseBody(StringBuilder sbTestMethodBody,
<del> String methodName, String baseClassName,
<del> String testBaseVariableName, String testBaseMethodName,
<del> String resultVariableName, String resultType, List<Param> params,
<del> List<ParamAssignment> paramAssignments, boolean isPublic,
<del> boolean isStatic) {
<del>
<del> String baseName;
<del>
<del> // create test-base
<del> if (!isStatic) {
<del> baseName = testBaseVariableName;
<del> sbTestMethodBody.append(testBaseVariableName).append("=")
<del> .append(testBaseMethodName).append("();");
<del> } else {
<del> baseName = baseClassName;
<del> }
<del>
<del> // create param assignments
<del> createParamAssignments(paramAssignments, sbTestMethodBody);
<del>
<del> // create param-list
<del> String paramNameList = createParamNameList(params);
<del>
<del> // result
<del> if (resultVariableName.length() > 0) {
<del> sbTestMethodBody.append(resultVariableName).append("=");
<del> }
<del>
<del> if (isPublic) {
<del> // method-call
<del> sbTestMethodBody.append(baseName).append(".").append(methodName)
<del> .append("(").append(paramNameList).append(");");
<del> } else {
<del>
<del> // method-call with white-box-call
<del> if (paramNameList.length() > 0) {
<del> paramNameList = ", new Object[]{" + paramNameList + "}";
<del> }
<del>
<del> if (isStatic) {
<del> baseName += ".class";
<del> }
<del>
<del> // TODO abfrage ob powermock oder jmockit
<del> // sbTestMethodBody.append("Whitebox.invokeMethod(").append(baseName).append(", ").append(QUOTES)
<del> // .append(methodName).append(QUOTES).append(paramValueList).append(");");
<del>
<del> sbTestMethodBody.append("Deencapsulation.invoke(").append(baseName)
<del> .append(", ").append(QUOTES).append(methodName)
<del> .append(QUOTES).append(paramNameList).append(");");
<del>
<del> }
<del> }
<del>
<del> protected String createParamNameList(List<Param> params) {
<del>
<del> StringBuilder sbParamList = new StringBuilder();
<del> String comma = "";
<del>
<del> for (Param param : params) {
<del> sbParamList.append(comma);
<del> sbParamList.append(param.getName());
<del>
<del> comma = ", ";
<del> }
<del>
<del> return sbParamList.toString();
<del>
<del> }
<del>
<del> protected void createParamInitializations(List<Param> params,
<del> StringBuilder methodBody) {
<del> // variable declaration and default initialization
<del> for (Param param : params) {
<del> methodBody.append(param.getType()).append(" ")
<del> .append(param.getName()).append(" = ")
<del> .append(JDTUtils.createInitValue(param.getType(), true))
<del> .append(";").append(RETURN);
<del> }
<del>
<del> }
<del>
<del> /**
<del> * Creates the param assignments
<del> *
<del> * @param paramAssignments
<del> * @param methodBody
<del> */
<del> protected void createParamAssignments(
<del> List<ParamAssignment> paramAssignments, StringBuilder methodBody) {
<del> for (ParamAssignment pa : paramAssignments) {
<del> methodBody.append(pa.getParamName()).append(" = ")
<del> .append(pa.getAssignment()).append(";\n");
<del> }
<del> }
<del>
<del> /**
<del> * Creates the method body for the assertions.
<del> *
<del> * @param sbTestMethodBody
<del> * @param resultVariableName
<del> * @param resultType
<del> * @param testBaseVariableName
<del> * @param tmlTestCase
<del> */
<del> protected void createAssertionsMethodBody(StringBuilder sbTestMethodBody,
<del> String resultVariableName, String resultType,
<del> String testBaseVariableName, TestCase tmlTestCase) {
<del>
<del> String baseType;
<del>
<del> for (Assertion tmlAssertion : tmlTestCase.getAssertion()) {
<del> // base
<del> String base;
<del> if ("{result}".equals(tmlAssertion.getBase())) {
<del> if ("".equals(resultVariableName)) {
<del> continue;
<del> }
<del>
<del> base = "result";
<del> baseType = resultType;
<del> } else {
<del> base = testBaseVariableName + "." + tmlAssertion.getBase()
<del> + "()";
<del> baseType = tmlAssertion.getBaseType();
<del> }
<del>
<del> // assertion-type
<del> AssertionType type = tmlAssertion.getType();
<del> String assertionType = createAssertionType(type, baseType);
<del>
<del> // Assertion
<del> sbTestMethodBody.append(RETURN + "Assert.").append(assertionType)
<del> .append("(");
<del>
<del> // message
<del> String message = "";
<del> if (tmlAssertion.getMessage() != null
<del> && tmlAssertion.getMessage().length() > 0) {
<del> message = tmlTestCase.getName() + ": "
<del> + tmlAssertion.getMessage();
<del> sbTestMethodBody.append(QUOTES).append(message).append(QUOTES)
<del> .append(", ");
<del> }
<del>
<del> // actual
<del> if (type == AssertionType.EQUALS
<del> || type == AssertionType.NOT_EQUALS) {
<del> // test-value
<del> String testValue = tmlAssertion.getValue();
<del> testValue = JDTUtils.formatValue(testValue, baseType);
<del> sbTestMethodBody.append(testValue).append(", ");
<del>
<del> // expected
<del> sbTestMethodBody.append(base);
<del>
<del> // delta
<del> if (JDTUtils.isNumber(baseType) && !JDTUtils.isArray(baseType)) {
<del> sbTestMethodBody.append(", 0");
<del> }
<del> } else {
<del> // expected
<del> sbTestMethodBody.append(base);
<del> }
<del>
<del> sbTestMethodBody.append(");");
<del> }
<del>
<del> }
<del>
<del> /**
<del> * Returns the assertion as String.
<del> *
<del> * @param type
<del> * @param baseType
<del> * @return assertion as String
<del> */
<del> protected String createAssertionType(AssertionType type, String baseType) {
<del> String assertionType = "assertEquals";
<del>
<del> if (type == AssertionType.EQUALS) {
<del> if (JDTUtils.isArray(baseType)) {
<del> assertionType = "assertArrayEquals";
<del> } else {
<del> assertionType = "assertEquals";
<del> }
<del> } else if (type == AssertionType.NOT_EQUALS) {
<del> assertionType = "assertNotEquals";
<del> } else if (type == AssertionType.IS_NULL) {
<del> assertionType = "assertNull";
<del> } else if (type == AssertionType.NOT_NULL) {
<del> assertionType = "assertNotNull";
<del> } else if (type == AssertionType.IS_TRUE) {
<del> assertionType = "assertTrue";
<del> } else if (type == AssertionType.IS_FALSE) {
<del> assertionType = "assertFalse";
<del> }
<del> return assertionType;
<del> }
<del>
<del> /**
<del> * Creates a parameter list.
<del> *
<del> * @param params
<del> * @return the created parameter list
<del> */
<del> protected String createParamList(List<Param> params) {
<del> Param tmlParam;
<del> StringBuilder sbParamList = new StringBuilder();
<del> boolean firstInit = true;
<del>
<del> for (int i = 0; i < params.size(); i++) {
<del> if (!firstInit)
<del> sbParamList.append(", ");
<del> else
<del> firstInit = false;
<del>
<del> tmlParam = params.get(i);
<del>
<del> sbParamList.append(tmlParam.getType()).append(" ")
<del> .append(tmlParam.getName());
<del> }
<del>
<del> return sbParamList.toString();
<del> }
<del>
<del> /**
<del> * Creates a parameter list with values.
<del> *
<del> * @param params
<del> * @param paramValues
<del> * @return the created parameter list with values
<del> */
<del> protected String createParamValueList(List<Param> params,
<del> List<String> paramValues) {
<del> StringBuilder sbParamList = new StringBuilder();
<del> boolean firstInit = true;
<del>
<del> Param tmlParam;
<del> String value, type;
<del>
<del> for (int i = 0; i < params.size()
<del> && (paramValues == null || i < paramValues.size()); i++) {
<del> if (!firstInit)
<del> sbParamList.append(", ");
<del> else
<del> firstInit = false;
<del>
<del> tmlParam = params.get(i);
<del> type = tmlParam.getType();
<del>
<del> if (paramValues != null) {
<del> value = paramValues.get(i);
<del> } else {
<del> value = "";
<del> }
<del>
<del> value = JDTUtils.formatValue(value, type);
<del>
<del> sbParamList.append(value);
<del> }
<del> return sbParamList.toString();
<del> }
<del>
<del> protected String getTestmethodPrefix() {
<del> if (testmethodPrefix == null)
<del> testmethodPrefix = JUTPreferences.getTestMethodPrefix();
<del>
<del> return testmethodPrefix;
<del> }
<del>
<del> /**
<del> * @return the test method post fix
<del> */
<del> protected String getTestmethodPostfix() {
<del> if (testmethodPostfix == null)
<del> testmethodPostfix = JUTPreferences.getTestMethodPostfix();
<del>
<del> return testmethodPostfix;
<del> }
<del>
<del> /**
<del> * Creates the annotation test priority.
<del> *
<del> * @return the created annotations
<del> */
<del> protected String createAnnoTestprio(Testprio testprio) {
<del> if (testprio == Testprio.DEFAULT)
<del> return ANNO_TESTPRIO + RETURN;
<del>
<del> return ANNO_TESTPRIO
<del> + "(prio=org.junit.tools.generator.model.tml.Testprio."
<del> + testprio + ")" + RETURN;
<del> }
<del>
<del> /**
<del> * Returns if the annotation generated is set.
<del> *
<del> * @param annotations
<del> * @return true if the annotation for the generated hooks is set.
<del> */
<del> protected boolean isGenerated(IAnnotation[] annotations) {
<del> for (IAnnotation annotation : annotations) {
<del> if (ANNO_GENERATED_NAME.equals(annotation.getElementName()))
<add> return null;
<add>
<add> // delete generated elements
<add> if (testClass.exists()) {
<add> deleteGeneratedElements(testClass, tmlSettings);
<add> }
<add>
<add> // increment task
<add> if (incrementTask(monitor))
<add> return null;
<add>
<add> // create standard-imports
<add> createStandardImports(testClass, tmlTest);
<add>
<add> // increment task
<add> if (incrementTask(monitor))
<add> return null;
<add>
<add> // create standard-class-fields
<add> createStandardClassFields(type, tmlTest, testClassName);
<add>
<add> // increment task
<add> if (incrementTask(monitor))
<add> return null;
<add>
<add> // create standard-methods
<add> createStandardMethods(type, tmlSettings);
<add>
<add> // increment task
<add> if (incrementTask(monitor))
<add> return null;
<add>
<add> // create test-base-methods
<add> if (writeTML) {
<add> createTestBaseMethods(type, tmlTest, baseClassName);
<add> } else {
<add> createTestBaseMethods(type, baseClass, baseClassName, model
<add> .getJUTElements().getConstructorsAndMethods()
<add> .getBaseClassConstructors(), testDataFactories);
<add> }
<add>
<add> // increment task
<add> if (incrementTask(monitor))
<add> return null;
<add>
<add> // delete test-methods
<add> for (IMethod methodToDelete : model.getMethodsToDelete()) {
<add> methodToDelete.delete(true, null);
<add> }
<add>
<add> // create test-methods
<add> if (createTestMethods(type, model.getMethodMap(),
<add> model.getMethodsToCreate(), tmlSettings, baseClassName,
<add> monitor, increment)) {
<add> return null;
<add> }
<add>
<add> // update test-methods (method-ref)
<add> updateExistingMethods(type.getCompilationUnit(), type,
<add> model.getExistingMethods());
<add>
<add> IPackageFragment testPackage = model.getJUTElements()
<add> .getClassesAndPackages().getTestPackage();
<add> testClass.createPackageDeclaration(testPackage.getElementName(), null);
<add>
<add> // create static standard-imports
<add> createStandardStaticImports(testClass);
<add>
<add> // save test-class
<add> testClass.save(null, true);
<add> testClass.makeConsistent(null);
<add> if (testClass.hasUnsavedChanges()) {
<add> testClass.commitWorkingCopy(true, null);
<add> }
<add>
<add> return testClass;
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> protected void updateExistingMethods(ICompilationUnit cu, IType cuType,
<add> HashMap<MethodRef, IMethod> existingMethods)
<add> throws JavaModelException, IllegalArgumentException,
<add> MalformedTreeException, BadLocationException {
<add> MethodRef methodRef;
<add> Annotation annotation;
<add>
<add> for (Entry<MethodRef, IMethod> entry : existingMethods.entrySet()) {
<add> // update method reference
<add> methodRef = entry.getKey();
<add> if (methodRef.isSignatureChanged()) {
<add> // delete old annotation
<add> for (IAnnotation iAnnotation : entry.getValue()
<add> .getAnnotations()) {
<add> if (iAnnotation instanceof Annotation) {
<add> annotation = (Annotation) iAnnotation;
<add>
<add> if (ANNO_METHOD_REF_NAME.equals(iAnnotation
<add> .getElementName())) {
<add> if (annotation.exists()) {
<add> annotation.delete(true, null);
<add> }
<add> }
<add>
<add> }
<add> }
<add>
<add> // create new annotation
<add> CompilationUnit astRoot = JDTUtils.createASTRoot(cu);
<add> MethodDeclaration md = JDTUtils.createMethodDeclaration(
<add> astRoot, entry.getValue());
<add>
<add> final ASTRewrite rewriter = ASTRewrite.create(md.getAST());
<add>
<add> NormalAnnotation newNormalAnnotation = rewriter.getAST()
<add> .newNormalAnnotation();
<add>
<add> newNormalAnnotation.setTypeName(astRoot.getAST().newName(
<add> "MethodRef"));
<add>
<add> newNormalAnnotation.values().add(
<add> createAnnotationMemberValuePair(astRoot.getAST(),
<add> "name", methodRef.getName()));
<add> newNormalAnnotation.values().add(
<add> createAnnotationMemberValuePair(astRoot.getAST(),
<add> "signature", methodRef.getSignatureNew()));
<add>
<add> rewriter.getListRewrite(md,
<add> MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(
<add> newNormalAnnotation, null);
<add>
<add> // apply changes
<add> TextEdit textEdit = rewriter.rewriteAST();
<add> Document document = new Document(cu.getSource());
<add> textEdit.apply(document);
<add> String newSource = document.get();
<add> // update of the compilation unit
<add> cu.getBuffer().setContents(newSource);
<add> }
<add> }
<add>
<add> }
<add>
<add> protected MemberValuePair createAnnotationMemberValuePair(final AST ast,
<add> final String name, final String value) {
<add>
<add> final MemberValuePair mvp = ast.newMemberValuePair();
<add> mvp.setName(ast.newSimpleName(name));
<add> StringLiteral stringLiteral = ast.newStringLiteral();
<add> stringLiteral.setLiteralValue(value);
<add> mvp.setValue(stringLiteral);
<add> return mvp;
<add> }
<add>
<add> protected void createTestBaseMethods(IType type,
<add> ICompilationUnit baseClass, String baseClassName,
<add> Vector<IMethod> constructors,
<add> List<ITestDataFactory> testDataFactories) throws JavaModelException {
<add> String testBaseMethodBody;
<add> StringBuilder classCreationChain;
<add> classCreationChain = new StringBuilder();
<add>
<add> String testBaseMethodName = "createTestSubject";
<add> if (type.getMethod(testBaseMethodName, null).exists()) {
<add> return;
<add> }
<add>
<add> JDTUtils.createClassCreationChain(baseClass.findPrimaryType(),
<add> classCreationChain, testDataFactories);
<add> testBaseMethodBody = " return " + classCreationChain.toString() + ";";
<add>
<add> JDTUtils.createMethod(type, MOD_PRIVATE, baseClassName,
<add> testBaseMethodName, null, null, testBaseMethodBody, false);
<add> }
<add>
<add> /**
<add> * Creates test base methods.
<add> *
<add> * @param type
<add> * @param tmlTest
<add> * @param testBaseName
<add> * @throws JavaModelException
<add> */
<add> protected void createTestBaseMethods(IType type, Test tmlTest,
<add> String testBaseName) throws JavaModelException {
<add> Settings tmlSettings = tmlTest.getSettings();
<add> TestBases tmlTestbases = tmlTest.getTestBases();
<add> if (tmlSettings == null || tmlTestbases == null) {
<add> return;
<add> }
<add>
<add> String testBaseMethodBody;
<add> String testBaseMethodName;
<add>
<add> for (Constructor tmlConstructor : tmlTestbases.getConstructor()) {
<add>
<add> for (TestBase tmlTestbase : tmlConstructor.getTestBase()) {
<add> testBaseMethodName = createTestBaseMethodName(tmlTestbase
<add> .getName());
<add>
<add> testBaseMethodBody = createTestBaseMethodBody(tmlTestbase,
<add> testBaseName, testBaseMethodName,
<add> tmlConstructor.getParam(), tmlSettings);
<add>
<add> JDTUtils.createMethod(type, MOD_PRIVATE, testBaseName,
<add> testBaseMethodName, "Exception", null,
<add> testBaseMethodBody, false);
<add> }
<add>
<add> if (tmlConstructor.getTestBase().size() == 0) {
<add> createTestBaseMethodDefault(type, testBaseName,
<add> tmlConstructor.getParam());
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * Creates the standard methods.
<add> *
<add> * @param type
<add> * @param tmlSettings
<add> * @throws JavaModelException
<add> */
<add> protected void createStandardMethods(IType type, Settings tmlSettings)
<add> throws JavaModelException {
<add> if (tmlSettings == null) {
<add> return;
<add> }
<add>
<add> if (tmlSettings.isSetUp()) {
<add> JDTUtils.createMethod(type, MOD_PUBLIC, TYPE_VOID,
<add> STANDARD_METHOD_BEFORE, EXCEPTION, null, "", false,
<add> ANNO_JUNIT_BEFORE);
<add> }
<add>
<add> if (tmlSettings.isSetUpBeforeClass()) {
<add> JDTUtils.createMethod(type, MOD_PUBLIC + MOD_STATIC_WITH_BLANK,
<add> TYPE_VOID, STANDARD_METHOD_BEFORE_ClASS, EXCEPTION, null,
<add> "", false, ANNO_JUNIT_BEFORE_CLASS);
<add> }
<add>
<add> if (tmlSettings.isTearDown()) {
<add> JDTUtils.createMethod(type, MOD_PUBLIC, TYPE_VOID,
<add> STANDARD_METHOD_AFTER, EXCEPTION, null, "", false,
<add> ANNO_JUNIT_AFTER);
<add> }
<add>
<add> if (tmlSettings.isTearDownBeforeClass()) {
<add> JDTUtils.createMethod(type, MOD_PUBLIC + MOD_STATIC_WITH_BLANK,
<add> TYPE_VOID, STANDARD_METHOD_AFTER_CLASS, "Exception", null,
<add> "", false, ANNO_JUNIT_AFTER_CLASS);
<add> }
<add> }
<add>
<add> /**
<add> * Create a hook after a method call.
<add> *
<add> * @param type
<add> * @param hookMethodName
<add> * @param param
<add> * @throws JavaModelException
<add> */
<add> protected void createHookAfterMethodCall(IType type, String hookMethodName,
<add> String param) throws JavaModelException {
<add> JDTUtils.createMethod(type, MOD_PRIVATE, TYPE_VOID, hookMethodName,
<add> "Exception", param, "", false);
<add> }
<add>
<add> /**
<add> * Increments the task.
<add> *
<add> * @param monitor
<add> * @return true if not canceled
<add> */
<add> protected boolean incrementTask(IProgressMonitor monitor) {
<add> return incrementTask(monitor, 1);
<add> }
<add>
<add> /**
<add> * Increments the task.
<add> *
<add> * @param monitor
<add> * @param i
<add> * @return true if not canceled
<add> */
<add> protected boolean incrementTask(IProgressMonitor monitor, int i) {
<add> if (monitor.isCanceled())
<add> return true;
<add> monitor.worked(i);
<add> return false;
<add> }
<add>
<add> /**
<add> * Deletes the generated elements.
<add> *
<add> * @param testClass
<add> * @param tmlSettings
<add> * @throws JavaModelException
<add> */
<add> protected void deleteGeneratedElements(ICompilationUnit testClass,
<add> Settings tmlSettings) throws JavaModelException {
<add> IType[] types = testClass.getTypes();
<add> IMethod method;
<add> IField field;
<add>
<add> for (IType type : types) {
<add> for (IJavaElement element : type.getChildren()) {
<add> if (element instanceof IMethod) {
<add> method = (IMethod) element;
<add>
<add> if (!deleteStandardMethod(
<add> method.getElementName().replace(".java", ""),
<add> tmlSettings)) {
<add> continue;
<add> }
<add> } else if (element instanceof IField) {
<add> field = (IField) element;
<add> if (isGenerated(field.getAnnotations())) {
<add> field.delete(true, null);
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * @param tmlSettings
<add> * @return isStandardMethod
<add> */
<add> protected boolean deleteStandardMethod(String methodName,
<add> Settings tmlSettings) {
<add> if (STANDARD_METHOD_BEFORE.equals(methodName)) {
<add> if (!tmlSettings.isSetUp()) {
<add> return true;
<add> } else {
<add> return false;
<add> }
<add> } else if (STANDARD_METHOD_BEFORE_ClASS.equals(methodName)) {
<add> if (!tmlSettings.isSetUpBeforeClass()) {
<add> return true;
<add> } else {
<add> return false;
<add> }
<add> } else if (STANDARD_METHOD_AFTER.equals(methodName)) {
<add> if (!tmlSettings.isTearDown()) {
<add> return true;
<add> } else {
<add> return false;
<add> }
<add> } else if (STANDARD_METHOD_AFTER_CLASS.equals(methodName)) {
<add> if (!tmlSettings.isTearDownBeforeClass()) {
<add> return true;
<add> } else {
<add> return false;
<add> }
<add> }
<ide> return true;
<ide> }
<ide>
<del> return false;
<del> }
<add> /**
<add> * Creates the test class frame.
<add> *
<add> * @param testCompilationUnit
<add> * @param tmlTest
<add> * @param testClassName
<add> * @return the created test class frame
<add> * @throws JavaModelException
<add> */
<add> protected IType createTestClassFrame(ICompilationUnit testCompilationUnit,
<add> Test tmlTest, String testClassName) throws JavaModelException {
<add> IType type = testCompilationUnit.getType(testClassName);
<add>
<add> if (!type.exists()) {
<add> return createTestClassFrame(testCompilationUnit, tmlTest,
<add> testClassName, null);
<add> } else {
<add> // check if recreation of test-class-frame is necessary
<add> Vector<Annotation> annotationsToDelete = getAnnotationsToDelete(
<add> type, tmlTest);
<add>
<add> if (annotationsToDelete != null) {
<add> for (Annotation annotation : annotationsToDelete)
<add> annotation.delete(true, null);
<add>
<add> String source = type.getSource();
<add> type.delete(true, null);
<add> return createTestClassFrame(testCompilationUnit, tmlTest,
<add> testClassName, source);
<add> }
<add> }
<add>
<add> return type;
<add> }
<add>
<add> /**
<add> * Returns the annotation to delete.
<add> *
<add> * @param type
<add> * @param tmlTest
<add> * @throws JavaModelException
<add> */
<add> protected Vector<Annotation> getAnnotationsToDelete(IType type, Test tmlTest)
<add> throws JavaModelException {
<add> Vector<Annotation> annotationsToDelete = new Vector<Annotation>();
<add> Annotation annotation;
<add> boolean recreationNecessary = false;
<add>
<add> for (IAnnotation iAnnotation : type.getAnnotations()) {
<add> if (iAnnotation instanceof Annotation) {
<add> annotation = (Annotation) iAnnotation;
<add>
<add> if (ANNO_GENERATED_NAME.equals(iAnnotation.getElementName())) {
<add> annotationsToDelete.add(annotation);
<add> IMemberValuePair[] memberValuePairs = annotation
<add> .getMemberValuePairs();
<add> for (IMemberValuePair valuePair : memberValuePairs) {
<add> if (!VERSION.equals(valuePair.getValue())) {
<add> recreationNecessary = true;
<add> break;
<add> }
<add> }
<add> } else if (ANNO_TESTPRIO_NAME.equals(iAnnotation
<add> .getElementName())) {
<add> annotationsToDelete.add(annotation);
<add> IMemberValuePair[] memberValuePairs = annotation
<add> .getMemberValuePairs();
<add>
<add> if (memberValuePairs.length == 0) {
<add> if (tmlTest.getTestPrio().compareTo(Testprio.DEFAULT) != 0)
<add> recreationNecessary = true;
<add> }
<add>
<add> for (IMemberValuePair valuePair : memberValuePairs) {
<add> if (!valuePair.getValue().toString()
<add> .endsWith(tmlTest.getTestPrio().toString())) {
<add> recreationNecessary = true;
<add> break;
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> if (!recreationNecessary)
<add> return null;
<add>
<add> return annotationsToDelete;
<add> }
<add>
<add> /**
<add> * Creates a test class frame.
<add> *
<add> * @param testCompilationUnit
<add> * @param tmlTest
<add> * @param testclassName
<add> * @param source
<add> * @return the created test class frame
<add> * @throws JavaModelException
<add> */
<add> protected IType createTestClassFrame(ICompilationUnit testCompilationUnit,
<add> Test tmlTest, String testclassName, String source)
<add> throws JavaModelException {
<add> // create annotations
<add> String annotations = createTestClassFrameAnnotations(tmlTest
<add> .getTestPrio());
<add>
<add> // create type
<add> String superType = "";
<add>
<add> if (source == null) {
<add> String customComment = getTestClassComment();
<add>
<add> superType = tmlTest.getSuperClass();
<add>
<add> String extendsStmt = "";
<add> if (!(superType == null || "".equals(superType))) {
<add> extendsStmt = " extends " + superType;
<add> } else {
<add> superType = "";
<add> }
<add>
<add> source = customComment + annotations.toString() + MOD_PUBLIC
<add> + " class " + testclassName + extendsStmt + "{ " + RETURN
<add> + "}";
<add> } else {
<add> source = annotations + source;
<add> }
<add>
<add> IType type = testCompilationUnit.createType(source, null, true, null);
<add>
<add> String superTypePackage = tmlTest.getSuperClassPackage();
<add> if (!"".equals(superType) && superTypePackage != null
<add> && !"".equals(superTypePackage)) {
<add> testCompilationUnit.createImport(
<add> superTypePackage + "." + superType, null, null);
<add> }
<add>
<add> return type;
<add> }
<add>
<add> protected String getTestClassComment() {
<add> return "";
<add> }
<add>
<add> /**
<add> * Creates the test class annotations.
<add> *
<add> * @param testprio
<add> * @return the created annotations
<add> */
<add> protected String createTestClassFrameAnnotations(Testprio testprio) {
<add> // create annotations
<add> StringBuilder annotations = new StringBuilder();
<add>
<add> // create generator-annotation
<add> annotations.append(createAnnoGenerated());
<add>
<add> // test-priority-annotation
<add> annotations.append(createAnnoTestprio(testprio));
<add>
<add> return annotations.toString();
<add> }
<add>
<add> /**
<add> * Creates the annotation generated.
<add> *
<add> * @return the created annotation
<add> */
<add> protected String createAnnoGenerated() {
<add> if (annoGenerated == null) {
<add> annoGenerated = GeneratorUtils.createAnnoGenerated();
<add> }
<add> return annoGenerated;
<add> }
<add>
<add> /**
<add> * Creates the standard imports.
<add> *
<add> * @param compilationUnit
<add> * @param tmlTest
<add> * @throws JavaModelException
<add> */
<add> protected void createStandardImports(ICompilationUnit compilationUnit,
<add> Test tmlTest) throws JavaModelException {
<add>
<add> compilationUnit.createImport("java.util.*", null, null);
<add> compilationUnit.createImport("org.junit.Assert", null, null);
<add> compilationUnit.createImport("org.junit.Test", null, null);
<add>
<add> if (tmlTest.getSettings().isLogger()) {
<add> compilationUnit
<add> .createImport("java.util.logging.Logger", null, null);
<add> }
<add> }
<add>
<add> protected void createStandardStaticImports(ICompilationUnit compilationUnit)
<add> throws JavaModelException {
<add> IJavaElement importAbove = null;
<add> IImportDeclaration[] imports = compilationUnit.getImports();
<add> if (imports.length > 0) {
<add> importAbove = imports[0];
<add> compilationUnit.createImport("org.junit.Assert.*", importAbove,
<add> Flags.AccStatic, null);
<add> }
<add> }
<add>
<add> /**
<add> * Create standard class fields.
<add> *
<add> * @param type
<add> * @param tmlTest
<add> * @param testclassName
<add> * @throws JavaModelException
<add> */
<add> protected void createStandardClassFields(IType type, Test tmlTest,
<add> String testclassName) throws JavaModelException {
<add> if (tmlTest.getSettings().isLogger()) {
<add> String logger = createAnnoGenerated() + " " + MOD_PRIVATE
<add> + " Logger logger = Logger.getLogger(" + testclassName
<add> + ".class.toString());";
<add> type.createField(logger, null, false, null);
<add> }
<add> }
<add>
<add> /**
<add> * Creates the test base method with default values.
<add> *
<add> * @param type
<add> * @param testbaseName
<add> * @param params
<add> * @throws JavaModelException
<add> */
<add> protected void createTestBaseMethodDefault(IType type, String testbaseName,
<add> List<Param> params) throws JavaModelException {
<add> if (defaultTestbaseMethodCreated)
<add> return;
<add>
<add> String paramValueList;
<add> if (params != null) {
<add> paramValueList = createParamValueList(params, null);
<add> } else {
<add> paramValueList = "";
<add> }
<add>
<add> StringBuilder sbMethodBody = new StringBuilder();
<add> sbMethodBody.append("return new ").append(testbaseName).append("(")
<add> .append(paramValueList).append(");");
<add>
<add> JDTUtils.createMethod(type, MOD_PRIVATE, testbaseName,
<add> TESTSUBJECT_METHOD_PREFIX, null, null, sbMethodBody.toString());
<add>
<add> defaultTestbaseMethodCreated = true;
<add> }
<add>
<add> /**
<add> * Creates the test base method name.
<add> *
<add> * @param tmlTestBaseName
<add> * @return test base method name
<add> */
<add> protected String createTestBaseMethodName(String tmlTestBaseName) {
<add> String testBaseName = GeneratorUtils.firstCharToUpper(tmlTestBaseName);
<add> String testBaseMethodName = TESTSUBJECT_METHOD_PREFIX + testBaseName;
<add> return testBaseMethodName;
<add> }
<add>
<add> /**
<add> * Creates the test base method body.
<add> *
<add> * @param tmlTestbase
<add> * @param testBaseName
<add> * @param testBaseMethodName
<add> * @param params
<add> * @param tmlSettings
<add> * @return the created test base method body
<add> */
<add> protected String createTestBaseMethodBody(TestBase tmlTestbase,
<add> String testBaseName, String testBaseMethodName, List<Param> params,
<add> Settings tmlSettings) {
<add>
<add> StringBuilder sbMethodBody = new StringBuilder();
<add>
<add> String constructorParams = "";
<add> if (params.size() > 0) {
<add> constructorParams = createParamValueList(params,
<add> tmlTestbase.getParamValue());
<add> }
<add>
<add> String testBaseMocks = createTestBaseMocks(tmlTestbase.getMocks());
<add> String testBaseVariableName = GeneratorUtils
<add> .firstCharToLower(testBaseName);
<add>
<add> // test-base initialization
<add> sbMethodBody.append(testBaseName).append(" ")
<add> .append(testBaseVariableName).append("=").append("new ")
<add> .append(testBaseName).append("(").append(constructorParams)
<add> .append(") {").append(testBaseMocks).append("};")
<add> .append(RETURN);
<add>
<add> // return
<add> sbMethodBody.append("return ").append(testBaseVariableName).append(";");
<add>
<add> return sbMethodBody.toString();
<add> }
<add>
<add> /**
<add> * Creates a parameter array list.
<add> *
<add> * @param params
<add> * @return parameter array list
<add> */
<add> protected String createParamArrayList(List<Param> params) {
<add> StringBuilder sbParamArrayList = new StringBuilder();
<add>
<add> boolean firstInit = true;
<add>
<add> for (int i = 0; i < params.size(); i++) {
<add> if (!firstInit) {
<add> sbParamArrayList.append(",");
<add> } else {
<add> firstInit = false;
<add> }
<add>
<add> sbParamArrayList.append("(").append(params.get(i).getType())
<add> .append(")paramList[").append(i).append("]");
<add> }
<add>
<add> return sbParamArrayList.toString();
<add> }
<add>
<add> /**
<add> * Creates a parameter array list.
<add> *
<add> * @param params
<add> * @param paramValues
<add> * @return parameter array list
<add> */
<add> protected String createParamArray(List<Param> params,
<add> List<String> paramValues) {
<add> StringBuilder sbParamArray = new StringBuilder();
<add>
<add> boolean firstInit = true;
<add>
<add> for (int i = 0; i < params.size() && i < paramValues.size(); i++) {
<add> if (firstInit) {
<add> sbParamArray.append("Object[] paramList = new Object[")
<add> .append(params.size()).append("];");
<add> firstInit = false;
<add> }
<add> sbParamArray
<add> .append("paramList[")
<add> .append(i)
<add> .append("] = ")
<add> .append(JDTUtils.formatValue(paramValues.get(i), params
<add> .get(i).getType())).append(";").append(RETURN);
<add> }
<add>
<add> return sbParamArray.toString();
<add> }
<add>
<add> /**
<add> * Creates the test base mocks.
<add> *
<add> * @param mocks
<add> * @return test base mocks
<add> */
<add> protected String createTestBaseMocks(Mocks mocks) {
<add> if (mocks == null)
<add> return "";
<add>
<add> StringBuilder sbMockMethods = new StringBuilder();
<add> String resultType;
<add> String resultValue;
<add> String modifier;
<add>
<add> for (Method tmlMockMethod : mocks.getMethod()) {
<add> if (tmlMockMethod.getResult() != null) {
<add> resultType = tmlMockMethod.getResult().getType();
<add> resultValue = tmlMockMethod.getResult().getValue();
<add> resultValue = JDTUtils.formatValue(resultValue, resultType);
<add> resultValue = "return " + resultValue + ";";
<add> } else {
<add> resultType = TYPE_VOID;
<add> resultValue = "";
<add> }
<add>
<add> modifier = tmlMockMethod.getModifier();
<add> if (MOD_PACKAGE.equals(modifier)) {
<add> modifier = "";
<add> }
<add>
<add> sbMockMethods.append(modifier).append(" ").append(resultType)
<add> .append(" ").append(tmlMockMethod.getName()).append("(")
<add> .append(createParamList(tmlMockMethod.getParam()))
<add> .append(") {").append(resultValue).append("}");
<add> }
<add>
<add> return sbMockMethods.toString();
<add> }
<add>
<add> /**
<add> * Creates the test methods.
<add> *
<add> * @param type
<add> * @param methodMap
<add> * @param methodsToCreate
<add> * @param tmlSettings
<add> * @param baseClassName
<add> * @param monitor
<add> * @param increment
<add> * @return true if the processing was stopped
<add> * @throws JavaModelException
<add> */
<add> protected boolean createTestMethods(IType type,
<add> HashMap<IMethod, Method> methodMap, List<IMethod> methodsToCreate,
<add> Settings tmlSettings, String baseClassName,
<add> IProgressMonitor monitor, int increment) throws JavaModelException {
<add>
<add> int i = 0;
<add>
<add> boolean failAssertions = tmlSettings.isFailAssertions();
<add>
<add> for (IMethod methodToCreate : methodsToCreate) {
<add> Method tmlMethod = methodMap.get(methodToCreate);
<add> createTestMethod(type, tmlMethod, baseClassName, failAssertions);
<add>
<add> if (i++ == increment) {
<add> i = 0;
<add> // increment task
<add> if (incrementTask(monitor))
<add> return true;
<add> }
<add> }
<add>
<add> return false;
<add> }
<add>
<add> /**
<add> * Creates a test method.
<add> *
<add> * @param type
<add> * @param tmlMethod
<add> * @param baseClassName
<add> * @param failAssertions
<add> * @param hookAfterMethodCall
<add> * @throws JavaModelException
<add> */
<add> protected void createTestMethod(IType type, Method tmlMethod,
<add> String baseClassName, boolean failAssertions)
<add> throws JavaModelException {
<add> String testMethodNamePrefix = getTestmethodPrefix();
<add> String testMethodNamePostfix = getTestmethodPostfix();
<add> String testMethodName;
<add> String testMethodBody;
<add>
<add> // create test-method-name
<add> if (testMethodNamePrefix != null && testMethodNamePrefix.length() > 0) {
<add> testMethodName = testMethodNamePrefix
<add> + GeneratorUtils.firstCharToUpper(tmlMethod.getName())
<add> + testMethodNamePostfix;
<add> } else {
<add> testMethodName = tmlMethod.getName() + testMethodNamePostfix;
<add> }
<add>
<add> // create test-method-body
<add> testMethodBody = createTestMethodBody(type, tmlMethod, testMethodName,
<add> baseClassName, failAssertions);
<add>
<add> // create method ref
<add> String annoMethodRef = GeneratorUtils.createAnnoMethodRef(
<add> tmlMethod.getName(), tmlMethod.getSignature());
<add>
<add> JDTUtils.createMethod(type, MOD_PUBLIC, TYPE_VOID, testMethodName,
<add> "Exception", null, testMethodBody, true, annoMethodRef,
<add> ANNO_JUNIT_TEST);
<add> }
<add>
<add> /**
<add> * Creates the test method body.
<add> *
<add> * @param type
<add> * @param tmlMethod
<add> * @param methodName
<add> * @param baseClassName
<add> * @param failAssertions
<add> * @param hookAfterMethodCall
<add> * @return the created test method body
<add> * @throws JavaModelException
<add> */
<add> protected String createTestMethodBody(IType type, Method tmlMethod,
<add> String methodName, String baseClassName, boolean failAssertions)
<add> throws JavaModelException {
<add> StringBuilder sbTestMethodBody = new StringBuilder();
<add> List<Param> params = tmlMethod.getParam();
<add> String testbaseMethodName = "";
<add> String testBaseVariableName = "testSubject"; // GeneratorUtils.firstCharToLower(baseClassName);
<add>
<add> // test-base-variable
<add> if (!tmlMethod.isStatic()) {
<add> sbTestMethodBody.append(baseClassName).append(" ")
<add> .append(testBaseVariableName).append(";");
<add> }
<add>
<add> // create param initializations
<add> createParamInitializations(params, sbTestMethodBody);
<add>
<add> // create result-variable
<add> Result result = tmlMethod.getResult();
<add> String resultVariableName = "";
<add> String resultType = "";
<add> if (result != null) {
<add> resultVariableName = result.getName();
<add> resultType = result.getType();
<add>
<add> sbTestMethodBody.append(resultType).append(" ")
<add> .append(resultVariableName).append(";");
<add> }
<add>
<add> List<TestCase> testCases = tmlMethod.getTestCase();
<add> boolean isPublic = MOD_PUBLIC.equals(tmlMethod.getModifier());
<add>
<add> for (TestCase tmlTestcase : testCases) {
<add> sbTestMethodBody.append(RETURN + RETURN + "// ")
<add> .append(tmlTestcase.getName()).append(RETURN);
<add>
<add> testbaseMethodName = createTestBaseMethodName(tmlTestcase
<add> .getTestBase());
<add>
<add> createTestCaseBody(sbTestMethodBody, tmlMethod.getName(),
<add> baseClassName, testBaseVariableName, testbaseMethodName,
<add> resultVariableName, resultType, params,
<add> tmlTestcase.getParamAssignments(), isPublic,
<add> tmlMethod.isStatic());
<add>
<add> // assertions
<add> createAssertionsMethodBody(sbTestMethodBody, resultVariableName,
<add> resultType, testBaseVariableName, tmlTestcase);
<add> }
<add>
<add> // fail-assertion
<add> if (failAssertions) {
<add> sbTestMethodBody.append(RETURN + RETURN).append(FAIL_ASSERTION);
<add> }
<add>
<add> return sbTestMethodBody.toString();
<add> }
<add>
<add> /**
<add> * Creates the test method body.
<add> *
<add> * @param sbTestMethodBody
<add> * @param methodName
<add> * @param baseClassName
<add> * @param testBaseVariableName
<add> * @param testBaseMethodName
<add> * @param resultVariableName
<add> * @param resultType
<add> * @param params
<add> * @param paramAssignments
<add> * @param isPublic
<add> * @param isStatic
<add> */
<add> protected void createTestCaseBody(StringBuilder sbTestMethodBody,
<add> String methodName, String baseClassName,
<add> String testBaseVariableName, String testBaseMethodName,
<add> String resultVariableName, String resultType, List<Param> params,
<add> List<ParamAssignment> paramAssignments, boolean isPublic,
<add> boolean isStatic) {
<add>
<add> String baseName;
<add>
<add> // create test-base
<add> if (!isStatic) {
<add> baseName = testBaseVariableName;
<add> sbTestMethodBody.append(testBaseVariableName).append("=")
<add> .append(testBaseMethodName).append("();");
<add> } else {
<add> baseName = baseClassName;
<add> }
<add>
<add> // create param assignments
<add> createParamAssignments(paramAssignments, sbTestMethodBody);
<add>
<add> // create param-list
<add> String paramNameList = createParamNameList(params);
<add>
<add> // result
<add> if (resultVariableName.length() > 0) {
<add> sbTestMethodBody.append(resultVariableName).append("=");
<add> }
<add>
<add> if (isPublic) {
<add> // method-call
<add> sbTestMethodBody.append(baseName).append(".").append(methodName)
<add> .append("(").append(paramNameList).append(");");
<add> } else {
<add>
<add> // method-call with white-box-call
<add> if (paramNameList.length() > 0) {
<add> paramNameList = ", new Object[]{" + paramNameList + "}";
<add> }
<add>
<add> if (isStatic) {
<add> baseName += ".class";
<add> }
<add>
<add> // TODO abfrage ob powermock oder jmockit
<add> // sbTestMethodBody.append("Whitebox.invokeMethod(").append(baseName).append(", ").append(QUOTES)
<add> // .append(methodName).append(QUOTES).append(paramValueList).append(");");
<add>
<add> sbTestMethodBody.append("Deencapsulation.invoke(").append(baseName)
<add> .append(", ").append(QUOTES).append(methodName)
<add> .append(QUOTES).append(paramNameList).append(");");
<add>
<add> }
<add> }
<add>
<add> protected String createParamNameList(List<Param> params) {
<add>
<add> StringBuilder sbParamList = new StringBuilder();
<add> String comma = "";
<add>
<add> for (Param param : params) {
<add> sbParamList.append(comma);
<add> sbParamList.append(param.getName());
<add>
<add> comma = ", ";
<add> }
<add>
<add> return sbParamList.toString();
<add>
<add> }
<add>
<add> protected void createParamInitializations(List<Param> params,
<add> StringBuilder methodBody) {
<add> // variable declaration and default initialization
<add> for (Param param : params) {
<add> methodBody.append(param.getType()).append(" ")
<add> .append(param.getName()).append(" = ")
<add> .append(JDTUtils.createInitValue(param.getType(), true))
<add> .append(";").append(RETURN);
<add> }
<add>
<add> }
<add>
<add> /**
<add> * Creates the param assignments
<add> *
<add> * @param paramAssignments
<add> * @param methodBody
<add> */
<add> protected void createParamAssignments(
<add> List<ParamAssignment> paramAssignments, StringBuilder methodBody) {
<add> for (ParamAssignment pa : paramAssignments) {
<add> methodBody.append(pa.getParamName()).append(" = ")
<add> .append(pa.getAssignment()).append(";\n");
<add> }
<add> }
<add>
<add> /**
<add> * Creates the method body for the assertions.
<add> *
<add> * @param sbTestMethodBody
<add> * @param resultVariableName
<add> * @param resultType
<add> * @param testBaseVariableName
<add> * @param tmlTestCase
<add> */
<add> protected void createAssertionsMethodBody(StringBuilder sbTestMethodBody,
<add> String resultVariableName, String resultType,
<add> String testBaseVariableName, TestCase tmlTestCase) {
<add>
<add> String baseType;
<add>
<add> for (Assertion tmlAssertion : tmlTestCase.getAssertion()) {
<add> // base
<add> String base;
<add> if ("{result}".equals(tmlAssertion.getBase())) {
<add> if ("".equals(resultVariableName)) {
<add> continue;
<add> }
<add>
<add> base = "result";
<add> baseType = resultType;
<add> } else {
<add> base = testBaseVariableName + "." + tmlAssertion.getBase()
<add> + "()";
<add> baseType = tmlAssertion.getBaseType();
<add> }
<add>
<add> // assertion-type
<add> AssertionType type = tmlAssertion.getType();
<add> String assertionType = createAssertionType(type, baseType);
<add>
<add> // Assertion
<add> sbTestMethodBody.append(RETURN + "Assert.").append(assertionType)
<add> .append("(");
<add>
<add> // message
<add> String message = "";
<add> if (tmlAssertion.getMessage() != null
<add> && tmlAssertion.getMessage().length() > 0) {
<add> message = tmlTestCase.getName() + ": "
<add> + tmlAssertion.getMessage();
<add> sbTestMethodBody.append(QUOTES).append(message).append(QUOTES)
<add> .append(", ");
<add> }
<add>
<add> // actual
<add> if (type == AssertionType.EQUALS
<add> || type == AssertionType.NOT_EQUALS) {
<add> // test-value
<add> String testValue = tmlAssertion.getValue();
<add> testValue = JDTUtils.formatValue(testValue, baseType);
<add> sbTestMethodBody.append(testValue).append(", ");
<add>
<add> // expected
<add> sbTestMethodBody.append(base);
<add>
<add> // delta
<add> if (JDTUtils.isNumber(baseType) && !JDTUtils.isArray(baseType)) {
<add> sbTestMethodBody.append(", 0");
<add> }
<add> } else {
<add> // expected
<add> sbTestMethodBody.append(base);
<add> }
<add>
<add> sbTestMethodBody.append(");");
<add> }
<add>
<add> }
<add>
<add> /**
<add> * Returns the assertion as String.
<add> *
<add> * @param type
<add> * @param baseType
<add> * @return assertion as String
<add> */
<add> protected String createAssertionType(AssertionType type, String baseType) {
<add> String assertionType = "assertEquals";
<add>
<add> if (type == AssertionType.EQUALS) {
<add> if (JDTUtils.isArray(baseType)) {
<add> assertionType = "assertArrayEquals";
<add> } else {
<add> assertionType = "assertEquals";
<add> }
<add> } else if (type == AssertionType.NOT_EQUALS) {
<add> assertionType = "assertNotEquals";
<add> } else if (type == AssertionType.IS_NULL) {
<add> assertionType = "assertNull";
<add> } else if (type == AssertionType.NOT_NULL) {
<add> assertionType = "assertNotNull";
<add> } else if (type == AssertionType.IS_TRUE) {
<add> assertionType = "assertTrue";
<add> } else if (type == AssertionType.IS_FALSE) {
<add> assertionType = "assertFalse";
<add> }
<add> return assertionType;
<add> }
<add>
<add> /**
<add> * Creates a parameter list.
<add> *
<add> * @param params
<add> * @return the created parameter list
<add> */
<add> protected String createParamList(List<Param> params) {
<add> Param tmlParam;
<add> StringBuilder sbParamList = new StringBuilder();
<add> boolean firstInit = true;
<add>
<add> for (int i = 0; i < params.size(); i++) {
<add> if (!firstInit)
<add> sbParamList.append(", ");
<add> else
<add> firstInit = false;
<add>
<add> tmlParam = params.get(i);
<add>
<add> sbParamList.append(tmlParam.getType()).append(" ")
<add> .append(tmlParam.getName());
<add> }
<add>
<add> return sbParamList.toString();
<add> }
<add>
<add> /**
<add> * Creates a parameter list with values.
<add> *
<add> * @param params
<add> * @param paramValues
<add> * @return the created parameter list with values
<add> */
<add> protected String createParamValueList(List<Param> params,
<add> List<String> paramValues) {
<add> StringBuilder sbParamList = new StringBuilder();
<add> boolean firstInit = true;
<add>
<add> Param tmlParam;
<add> String value, type;
<add>
<add> for (int i = 0; i < params.size()
<add> && (paramValues == null || i < paramValues.size()); i++) {
<add> if (!firstInit)
<add> sbParamList.append(", ");
<add> else
<add> firstInit = false;
<add>
<add> tmlParam = params.get(i);
<add> type = tmlParam.getType();
<add>
<add> if (paramValues != null) {
<add> value = paramValues.get(i);
<add> } else {
<add> value = "";
<add> }
<add>
<add> value = JDTUtils.formatValue(value, type);
<add>
<add> sbParamList.append(value);
<add> }
<add> return sbParamList.toString();
<add> }
<add>
<add> protected String getTestmethodPrefix() {
<add> if (testmethodPrefix == null)
<add> testmethodPrefix = JUTPreferences.getTestMethodPrefix();
<add>
<add> return testmethodPrefix;
<add> }
<add>
<add> /**
<add> * @return the test method post fix
<add> */
<add> protected String getTestmethodPostfix() {
<add> if (testmethodPostfix == null)
<add> testmethodPostfix = JUTPreferences.getTestMethodPostfix();
<add>
<add> return testmethodPostfix;
<add> }
<add>
<add> /**
<add> * Creates the annotation test priority.
<add> *
<add> * @return the created annotations
<add> */
<add> protected String createAnnoTestprio(Testprio testprio) {
<add> if (testprio == Testprio.DEFAULT)
<add> return ANNO_TESTPRIO + RETURN;
<add>
<add> return ANNO_TESTPRIO
<add> + "(prio=org.junit.tools.generator.model.tml.Testprio."
<add> + testprio + ")" + RETURN;
<add> }
<add>
<add> /**
<add> * Returns if the annotation generated is set.
<add> *
<add> * @param annotations
<add> * @return true if the annotation for the generated hooks is set.
<add> */
<add> protected boolean isGenerated(IAnnotation[] annotations) {
<add> for (IAnnotation annotation : annotations) {
<add> if (ANNO_GENERATED_NAME.equals(annotation.getElementName()))
<add> return true;
<add> }
<add>
<add> return false;
<add> }
<ide>
<ide> } |
||
Java | apache-2.0 | 30042d0305a1658da66bd1cb5224d1ce1c3863b2 | 0 | amith01994/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,da1z/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,ibinti/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,samthor/intellij-community,hurricup/intellij-community,ryano144/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,holmes/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,signed/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,fnouama/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,izonder/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,signed/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,samthor/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,diorcety/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,kool79/intellij-community,signed/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,kool79/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,da1z/intellij-community,robovm/robovm-studio,kool79/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,semonte/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,supersven/intellij-community,kdwink/intellij-community,vladmm/intellij-community,consulo/consulo,michaelgallacher/intellij-community,signed/intellij-community,samthor/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,kool79/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,allotria/intellij-community,asedunov/intellij-community,samthor/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,kool79/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,semonte/intellij-community,asedunov/intellij-community,semonte/intellij-community,adedayo/intellij-community,retomerz/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,ernestp/consulo,ftomassetti/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,amith01994/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,ibinti/intellij-community,kool79/intellij-community,supersven/intellij-community,diorcety/intellij-community,vladmm/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,ernestp/consulo,jagguli/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,allotria/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,signed/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,robovm/robovm-studio,retomerz/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,fitermay/intellij-community,fnouama/intellij-community,da1z/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,clumsy/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,allotria/intellij-community,izonder/intellij-community,da1z/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,slisson/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,samthor/intellij-community,fitermay/intellij-community,allotria/intellij-community,semonte/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,fitermay/intellij-community,dslomov/intellij-community,FHannes/intellij-community,apixandru/intellij-community,amith01994/intellij-community,semonte/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,allotria/intellij-community,allotria/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,izonder/intellij-community,apixandru/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,consulo/consulo,xfournet/intellij-community,fnouama/intellij-community,holmes/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,akosyakov/intellij-community,supersven/intellij-community,slisson/intellij-community,slisson/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,retomerz/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,da1z/intellij-community,vvv1559/intellij-community,supersven/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,mglukhikh/intellij-community,holmes/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,retomerz/intellij-community,FHannes/intellij-community,da1z/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,signed/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,supersven/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,ernestp/consulo,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,supersven/intellij-community,adedayo/intellij-community,signed/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,holmes/intellij-community,samthor/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,dslomov/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,supersven/intellij-community,asedunov/intellij-community,asedunov/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,ryano144/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,signed/intellij-community,ibinti/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,supersven/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,kool79/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,holmes/intellij-community,ryano144/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,caot/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,caot/intellij-community,jagguli/intellij-community,robovm/robovm-studio,kdwink/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,retomerz/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,kdwink/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,ernestp/consulo,fnouama/intellij-community,vladmm/intellij-community,allotria/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,samthor/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,blademainer/intellij-community,blademainer/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,izonder/intellij-community,wreckJ/intellij-community,semonte/intellij-community,ernestp/consulo,consulo/consulo,alphafoobar/intellij-community,ibinti/intellij-community,xfournet/intellij-community,samthor/intellij-community,hurricup/intellij-community,caot/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,da1z/intellij-community,petteyg/intellij-community,semonte/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,caot/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,fnouama/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,adedayo/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,kdwink/intellij-community,robovm/robovm-studio,ibinti/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,hurricup/intellij-community,diorcety/intellij-community,kdwink/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,consulo/consulo,fitermay/intellij-community,wreckJ/intellij-community,caot/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,ernestp/consulo,Lekanich/intellij-community,apixandru/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,ryano144/intellij-community,jagguli/intellij-community,blademainer/intellij-community,caot/intellij-community,suncycheng/intellij-community,semonte/intellij-community,kool79/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,fnouama/intellij-community,signed/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,izonder/intellij-community,holmes/intellij-community,retomerz/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,consulo/consulo,vladmm/intellij-community,izonder/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,amith01994/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,semonte/intellij-community,suncycheng/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,semonte/intellij-community,slisson/intellij-community,vvv1559/intellij-community,izonder/intellij-community,ibinti/intellij-community,ryano144/intellij-community,robovm/robovm-studio,blademainer/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community | /*
* 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.
*/
package org.jetbrains.idea.maven.dom;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiReference;
import org.jetbrains.idea.maven.indices.MavenIndicesTestFixture;
import org.jetbrains.idea.maven.indices.MavenProjectIndicesManager;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class MavenExtensionCompletionAndResolutionTest extends MavenDomWithIndicesTestCase {
@Override
protected MavenIndicesTestFixture createIndicesFixture() {
return new MavenIndicesTestFixture(myDir, myProject, "plugins");
}
@Override
protected void setUpInWriteAction() throws Exception {
super.setUpInWriteAction();
importProject("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>");
}
public void testGroupIdCompletion() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <extension>" +
" <groupId><caret></groupId>" +
" </extension>" +
" </extensions>" +
"</build>");
assertCompletionVariants(myProjectPom, "test", "org.apache.maven.plugins", "org.codehaus.mojo");
}
public void testArtifactIdCompletion() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <extension>" +
" <groupId>org.apache.maven.plugins</groupId>" +
" <artifactId><caret></artifactId>" +
" </extension>" +
" </extensions>" +
"</build>");
List<String> actual = getCompletionVariants(myProjectPom);
if (!new HashSet<String>(actual).equals(new HashSet<String>(Arrays.asList("maven-compiler-plugin", "maven-war-plugin", "maven-eclipse-plugin", "maven-surefire-plugin")))) {
MavenProjectIndicesManager instance = MavenProjectIndicesManager.getInstance(myProject);
System.out.println("GetArtifacts: " + instance.getArtifactIds("org.apache.maven.plugins"));
System.out.println("Indexes: " + instance.getIndices());
throw new AssertionError("GetArtifacts: " + instance.getArtifactIds("org.apache.maven.plugins") + "Indexes: " + instance.getIndices());
}
assertUnorderedElementsAreEqual(actual, "maven-compiler-plugin", "maven-war-plugin", "maven-eclipse-plugin", "maven-surefire-plugin");
}
public void testArtifactWithoutGroupCompletion() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <extension>" +
" <artifactId><caret></artifactId>" +
" </extension>" +
" </extensions>" +
"</build>");
assertCompletionVariants(myProjectPom,
"maven-compiler-plugin",
"maven-war-plugin",
"maven-surefire-plugin",
"build-helper-maven-plugin",
"maven-eclipse-plugin");
}
public void testResolving() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <extension>" +
" <artifactId><caret>maven-compiler-plugin</artifactId>" +
" </extension>" +
" </extensions>" +
"</build>");
String pluginPath = "plugins/org/apache/maven/plugins/maven-compiler-plugin/2.0.2/maven-compiler-plugin-2.0.2.pom";
String filePath = myIndicesFixture.getRepositoryHelper().getTestDataPath(pluginPath);
VirtualFile f = LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath);
assertResolved(myProjectPom, findPsiFile(f));
}
public void testResolvingAbsentPlugins() throws Exception {
removeFromLocalRepository("org/apache/maven/plugins/maven-compiler-plugin");
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <extension>" +
" <artifactId><caret>maven-compiler-plugin</artifactId>" +
" </extension>" +
" </extensions>" +
"</build>");
PsiReference ref = getReferenceAtCaret(myProjectPom);
assertNotNull(ref);
ref.resolve(); // shouldn't throw;
}
public void testDoNotHighlightAbsentGroupIdAndVersion() throws Throwable {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <extension>" +
" <artifactId>maven-compiler-plugin</artifactId>" +
" </extension>" +
" </extensions>" +
"</build>");
checkHighlighting();
}
public void testHighlightingAbsentArtifactId() throws Throwable {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <<error descr=\"'artifactId' child tag should be defined\">extension</error>>" +
" </extension>" +
" </extensions>" +
"</build>");
checkHighlighting();
}
}
| plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenExtensionCompletionAndResolutionTest.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.
*/
package org.jetbrains.idea.maven.dom;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiReference;
import org.jetbrains.idea.maven.indices.MavenIndicesTestFixture;
import org.jetbrains.idea.maven.indices.MavenProjectIndicesManager;
import java.util.List;
public class MavenExtensionCompletionAndResolutionTest extends MavenDomWithIndicesTestCase {
@Override
protected MavenIndicesTestFixture createIndicesFixture() {
return new MavenIndicesTestFixture(myDir, myProject, "plugins");
}
@Override
protected void setUpInWriteAction() throws Exception {
super.setUpInWriteAction();
importProject("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>");
}
public void testGroupIdCompletion() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <extension>" +
" <groupId><caret></groupId>" +
" </extension>" +
" </extensions>" +
"</build>");
assertCompletionVariants(myProjectPom, "test", "org.apache.maven.plugins", "org.codehaus.mojo");
}
public void testArtifactIdCompletion() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <extension>" +
" <groupId>org.apache.maven.plugins</groupId>" +
" <artifactId><caret></artifactId>" +
" </extension>" +
" </extensions>" +
"</build>");
List<String> actual = getCompletionVariants(myProjectPom);
if (actual.isEmpty()) {
MavenProjectIndicesManager instance = MavenProjectIndicesManager.getInstance(myProject);
System.out.println("GetArtifacts: " + instance.getArtifactIds("org.apache.maven.plugins"));
System.out.println("Indexes: " + instance.getIndices());
throw new AssertionError("GetArtifacts: " + instance.getArtifactIds("org.apache.maven.plugins") + "Indexes: " + instance.getIndices());
}
assertUnorderedElementsAreEqual(actual, "maven-compiler-plugin", "maven-war-plugin", "maven-eclipse-plugin", "maven-surefire-plugin");
}
public void testArtifactWithoutGroupCompletion() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <extension>" +
" <artifactId><caret></artifactId>" +
" </extension>" +
" </extensions>" +
"</build>");
assertCompletionVariants(myProjectPom,
"maven-compiler-plugin",
"maven-war-plugin",
"maven-surefire-plugin",
"build-helper-maven-plugin",
"maven-eclipse-plugin");
}
public void testResolving() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <extension>" +
" <artifactId><caret>maven-compiler-plugin</artifactId>" +
" </extension>" +
" </extensions>" +
"</build>");
String pluginPath = "plugins/org/apache/maven/plugins/maven-compiler-plugin/2.0.2/maven-compiler-plugin-2.0.2.pom";
String filePath = myIndicesFixture.getRepositoryHelper().getTestDataPath(pluginPath);
VirtualFile f = LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath);
assertResolved(myProjectPom, findPsiFile(f));
}
public void testResolvingAbsentPlugins() throws Exception {
removeFromLocalRepository("org/apache/maven/plugins/maven-compiler-plugin");
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <extension>" +
" <artifactId><caret>maven-compiler-plugin</artifactId>" +
" </extension>" +
" </extensions>" +
"</build>");
PsiReference ref = getReferenceAtCaret(myProjectPom);
assertNotNull(ref);
ref.resolve(); // shouldn't throw;
}
public void testDoNotHighlightAbsentGroupIdAndVersion() throws Throwable {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <extension>" +
" <artifactId>maven-compiler-plugin</artifactId>" +
" </extension>" +
" </extensions>" +
"</build>");
checkHighlighting();
}
public void testHighlightingAbsentArtifactId() throws Throwable {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<build>" +
" <extensions>" +
" <<error descr=\"'artifactId' child tag should be defined\">extension</error>>" +
" </extension>" +
" </extensions>" +
"</build>");
checkHighlighting();
}
}
| Add additional loggining to understand cause of maven test fail
| plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenExtensionCompletionAndResolutionTest.java | Add additional loggining to understand cause of maven test fail | <ide><path>lugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenExtensionCompletionAndResolutionTest.java
<ide> import org.jetbrains.idea.maven.indices.MavenIndicesTestFixture;
<ide> import org.jetbrains.idea.maven.indices.MavenProjectIndicesManager;
<ide>
<add>import java.util.Arrays;
<add>import java.util.HashSet;
<ide> import java.util.List;
<ide>
<ide> public class MavenExtensionCompletionAndResolutionTest extends MavenDomWithIndicesTestCase {
<ide>
<ide> List<String> actual = getCompletionVariants(myProjectPom);
<ide>
<del> if (actual.isEmpty()) {
<add> if (!new HashSet<String>(actual).equals(new HashSet<String>(Arrays.asList("maven-compiler-plugin", "maven-war-plugin", "maven-eclipse-plugin", "maven-surefire-plugin")))) {
<ide> MavenProjectIndicesManager instance = MavenProjectIndicesManager.getInstance(myProject);
<ide> System.out.println("GetArtifacts: " + instance.getArtifactIds("org.apache.maven.plugins"));
<ide> System.out.println("Indexes: " + instance.getIndices()); |
|
JavaScript | mit | 69e124b14b183777be92aebceea6ff74345b4f37 | 0 | ZachLamb/book-1,ZachLamb/book-1,ZachLamb/book-1 | var _ = require('lodash')
var random_name = require('node-random-name');
var Firebase = require('firebase');
// San Francisco
var city_location = {
lat: 37.78,
lon: -122.41
}
var radius = 0.03
// simualate a random person entering, staying for a duration, and leaving
function simulate() {
// generate a random person with a random name,
// random location, and random duration
var name = random_name()
var duration = 1 + 5 * Math.random()
var lat = city_location.lat + radius * (Math.random() - 0.5) * 2
var lon = city_location.lon + radius * (Math.random() - 0.5) * 2
var person = {
name: name,
duration: duration,
lat: lat,
lon: lon
}
// simulate this person entering
enter(person)
// simulate this person leaving after 'duration' seconds
setTimeout(function() {
leave(person)
}, duration * 1000)
}
function enter(person) {
console.log('enter', person)
// Put this person in the Firebase
var ref = new Firebase('https://hello-ucdd2016.firebaseio.com/people')
ref.child(person.name).set({
lat: person.lat,
lon: person.lon,
name : person.name
});
}
function leave(person) {
console.log('leave', person)
var ref = new Firebase('https://hello-ucdd2016.firebaseio.com/people')
var onComplete = function(error) {
if (error) {
console.log('Leave Synchronization failed');
} else {
console.log('Leave Synchronization succeeded');
}
};
ref.child(person.name).remove(onComplete);
}
function clear() {
// TODO: remove all people from the Firebase
var ref = new Firebase('https://hello-ucdd2016.firebaseio.com/people')
var onComplete = function(error) {
if (error) {
console.log('Clear Synchronization failed');
} else {
console.log('Clear Synchronization succeeded');
}
};
ref.remove(onComplete)
}
// clear the firebase, so that the simulation always starts from no one
clear()
// run each second
setInterval(simulate, 2000) | workers/simulate-parking-customers.js | var _ = require('lodash')
var random_name = require('node-random-name');
var Firebase = require('firebase');
// San Francisco
var city_location = {
lat: 37.78,
lon: -122.41
}
var radius = 0.03
// simualate a random person entering, staying for a duration, and leaving
function simulate() {
// generate a random person with a random name,
// random location, and random duration
var name = random_name()
var duration = 1 + 5 * Math.random()
var lat = city_location.lat + radius * (Math.random() - 0.5) * 2
var lon = city_location.lon + radius * (Math.random() - 0.5) * 2
var person = {
name: name,
duration: duration,
lat: lat,
lon: lon
}
// simulate this person entering
enter(person)
// simulate this person leaving after 'duration' seconds
setTimeout(function() {
leave(person)
}, duration * 1000)
}
function enter(person) {
console.log('enter', person)
// Put this person in the Firebase
var ref = new Firebase('https://hello-ucdd2016.firebaseio.com/people')
ref.child(person.name).set({
lat: person.lat,
lon: person.lon
});
}
function leave(person) {
console.log('leave', person)
// TODO: remove this person from the Firebase
// var ref = new Firebase('your-firebase-url')
// ...
var ref = new Firebase('https://hello-ucdd2016.firebaseio.com/people')
var onComplete = function(error) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
}
};
ref.child(person.name).remove(onComplete);
}
function clear() {
// TODO: remove all people from the Firebase
var ref = new Firebase('https://hello-ucdd2016.firebaseio.com/people')
ref.remove()
}
// clear the firebase, so that the simulation always starts from no one
clear()
// run each second
setInterval(simulate, 2000) | fixmerge
| workers/simulate-parking-customers.js | fixmerge | <ide><path>orkers/simulate-parking-customers.js
<ide> var ref = new Firebase('https://hello-ucdd2016.firebaseio.com/people')
<ide> ref.child(person.name).set({
<ide> lat: person.lat,
<del> lon: person.lon
<add> lon: person.lon,
<add> name : person.name
<ide> });
<ide> }
<ide>
<ide> function leave(person) {
<ide> console.log('leave', person)
<del> // TODO: remove this person from the Firebase
<del> // var ref = new Firebase('your-firebase-url')
<del> // ...
<ide> var ref = new Firebase('https://hello-ucdd2016.firebaseio.com/people')
<ide> var onComplete = function(error) {
<ide> if (error) {
<del> console.log('Synchronization failed');
<add> console.log('Leave Synchronization failed');
<ide> } else {
<del> console.log('Synchronization succeeded');
<add> console.log('Leave Synchronization succeeded');
<ide> }
<ide> };
<ide>
<ide> function clear() {
<ide> // TODO: remove all people from the Firebase
<ide> var ref = new Firebase('https://hello-ucdd2016.firebaseio.com/people')
<del> ref.remove()
<add> var onComplete = function(error) {
<add> if (error) {
<add> console.log('Clear Synchronization failed');
<add> } else {
<add> console.log('Clear Synchronization succeeded');
<add> }
<add> };
<add>
<add> ref.remove(onComplete)
<ide> }
<ide> // clear the firebase, so that the simulation always starts from no one
<ide> clear() |
|
Java | apache-2.0 | 77545414e7e806d4846f05525cd7436139dc6fe1 | 0 | evigeant/liquibase,dbmanul/dbmanul,liquibase/liquibase,cleiter/liquibase,syncron/liquibase,maberle/liquibase,Vampire/liquibase,C0mmi3/liquibase,rkrzewski/liquibase,iherasymenko/liquibase,vbekiaris/liquibase,instantdelay/liquibase,lazaronixon/liquibase,maberle/liquibase,mwaylabs/liquibase,tjardo83/liquibase,vbekiaris/liquibase,AlisonSouza/liquibase,danielkec/liquibase,pellcorp/liquibase,gquintana/liquibase,FreshGrade/liquibase,dprguard2000/liquibase,klopfdreh/liquibase,C0mmi3/liquibase,ZEPowerGroup/liquibase,jimmycd/liquibase,evigeant/liquibase,FreshGrade/liquibase,Willem1987/liquibase,cbotiza/liquibase,gquintana/liquibase,Datical/liquibase,CoderPaulK/liquibase,rkrzewski/liquibase,iherasymenko/liquibase,mattbertolini/liquibase,lazaronixon/liquibase,talklittle/liquibase,mbreslow/liquibase,syncron/liquibase,vbekiaris/liquibase,EVODelavega/liquibase,pellcorp/liquibase,C0mmi3/liquibase,jimmycd/liquibase,mortegac/liquibase,foxel/liquibase,russ-p/liquibase,mortegac/liquibase,dyk/liquibase,fbiville/liquibase,vast-engineering/liquibase,AlisonSouza/liquibase,danielkec/liquibase,liquibase/liquibase,cbotiza/liquibase,syncron/liquibase,mbreslow/liquibase,fossamagna/liquibase,fossamagna/liquibase,russ-p/liquibase,balazs-zsoldos/liquibase,evigeant/liquibase,syncron/liquibase,NSIT/liquibase,ArloL/liquibase,tjardo83/liquibase,OculusVR/shanghai-liquibase,fossamagna/liquibase,CoderPaulK/liquibase,hbogaards/liquibase,russ-p/liquibase,instantdelay/liquibase,foxel/liquibase,foxel/liquibase,hbogaards/liquibase,ivaylo5ev/liquibase,OpenCST/liquibase,mortegac/liquibase,evigeant/liquibase,vbekiaris/liquibase,Datical/liquibase,AlisonSouza/liquibase,vfpfafrf/liquibase,vfpfafrf/liquibase,vast-engineering/liquibase,gquintana/liquibase,Datical/liquibase,fbiville/liquibase,dprguard2000/liquibase,OpenCST/liquibase,lazaronixon/liquibase,balazs-zsoldos/liquibase,OculusVR/shanghai-liquibase,dbmanul/dbmanul,adriens/liquibase,maberle/liquibase,lazaronixon/liquibase,mwaylabs/liquibase,Datical/liquibase,mwaylabs/liquibase,dprguard2000/liquibase,NSIT/liquibase,rkrzewski/liquibase,dbmanul/dbmanul,OculusVR/shanghai-liquibase,adriens/liquibase,mwaylabs/liquibase,instantdelay/liquibase,EVODelavega/liquibase,danielkec/liquibase,ZEPowerGroup/liquibase,dyk/liquibase,NSIT/liquibase,mortegac/liquibase,Willem1987/liquibase,ivaylo5ev/liquibase,liquibase/liquibase,OculusVR/shanghai-liquibase,fbiville/liquibase,vfpfafrf/liquibase,mbreslow/liquibase,adriens/liquibase,Willem1987/liquibase,dyk/liquibase,dyk/liquibase,pellcorp/liquibase,vast-engineering/liquibase,talklittle/liquibase,tjardo83/liquibase,mattbertolini/liquibase,FreshGrade/liquibase,C0mmi3/liquibase,cleiter/liquibase,talklittle/liquibase,iherasymenko/liquibase,Vampire/liquibase,EVODelavega/liquibase,tjardo83/liquibase,foxel/liquibase,fbiville/liquibase,hbogaards/liquibase,balazs-zsoldos/liquibase,balazs-zsoldos/liquibase,CoderPaulK/liquibase,cbotiza/liquibase,CoderPaulK/liquibase,talklittle/liquibase,FreshGrade/liquibase,ArloL/liquibase,cleiter/liquibase,danielkec/liquibase,maberle/liquibase,ArloL/liquibase,EVODelavega/liquibase,dprguard2000/liquibase,mattbertolini/liquibase,vfpfafrf/liquibase,instantdelay/liquibase,klopfdreh/liquibase,gquintana/liquibase,ZEPowerGroup/liquibase,OpenCST/liquibase,OpenCST/liquibase,jimmycd/liquibase,Willem1987/liquibase,jimmycd/liquibase,russ-p/liquibase,cbotiza/liquibase,klopfdreh/liquibase,klopfdreh/liquibase,dbmanul/dbmanul,hbogaards/liquibase,Vampire/liquibase,pellcorp/liquibase,vast-engineering/liquibase,cleiter/liquibase,mattbertolini/liquibase,AlisonSouza/liquibase,iherasymenko/liquibase,mbreslow/liquibase,NSIT/liquibase | package liquibase.ant;
import liquibase.CompositeFileOpener;
import liquibase.FileOpener;
import liquibase.FileSystemFileOpener;
import liquibase.Liquibase;
import liquibase.util.LiquibaseUtil;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.HibernateDatabase;
import liquibase.exception.JDBCException;
import liquibase.log.LogFactory;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Reference;
import java.io.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.sql.Connection;
import java.sql.Driver;
import java.util.*;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* Base class for all Ant LiquiBase tasks. This class sets up LiquiBase and defines parameters
* that are common to all tasks.
*/
public class BaseLiquibaseTask extends Task {
private String changeLogFile;
private String driver;
private String url;
private String username;
private String password;
protected Path classpath;
private boolean promptOnNonLocalDatabase = false;
private String currentDateTimeFunction;
private String contexts;
private String outputFile;
private String defaultSchemaName;
private String databaseClass;
private Map<String, Object> changeLogProperties = new HashMap<String, Object>();
public BaseLiquibaseTask() {
super();
new LogRedirector(this).redirectLogger();
}
public boolean isPromptOnNonLocalDatabase() {
return promptOnNonLocalDatabase;
}
public void setPromptOnNonLocalDatabase(boolean promptOnNonLocalDatabase) {
this.promptOnNonLocalDatabase = promptOnNonLocalDatabase;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
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 getChangeLogFile() {
return changeLogFile;
}
public void setChangeLogFile(String changeLogFile) {
this.changeLogFile = changeLogFile;
}
public Path createClasspath() {
if (this.classpath == null) {
this.classpath = new Path(getProject());
}
return this.classpath.createPath();
}
public void setClasspathRef(Reference r) {
createClasspath().setRefid(r);
}
public String getCurrentDateTimeFunction() {
return currentDateTimeFunction;
}
public void setCurrentDateTimeFunction(String currentDateTimeFunction) {
this.currentDateTimeFunction = currentDateTimeFunction;
}
public String getOutputFile() {
return outputFile;
}
public void setOutputFile(String outputFile) {
this.outputFile = outputFile;
}
public Writer createOutputWriter() throws IOException {
if (outputFile == null) {
return null;
}
return new FileWriter(new File(getOutputFile()));
}
public PrintStream createPrintStream() throws IOException {
if (outputFile == null) {
return null;
}
return new PrintStream(new File(getOutputFile()));
}
public String getDefaultSchemaName() {
return defaultSchemaName;
}
public void setDefaultSchemaName(String defaultSchemaName) {
this.defaultSchemaName = defaultSchemaName;
}
public void addConfiguredChangeLogProperty(ChangeLogProperty changeLogProperty) {
changeLogProperties.put(changeLogProperty.getName(), changeLogProperty.getValue());
}
protected Liquibase createLiquibase() throws Exception {
FileOpener antFO = new AntFileOpener(getProject(), classpath);
FileOpener fsFO = new FileSystemFileOpener();
Database database = createDatabaseObject(getDriver(), getUrl(), getUsername(), getPassword(), getDefaultSchemaName(),getDatabaseClass());
String changeLogFile = null;
if (getChangeLogFile() != null) {
changeLogFile = getChangeLogFile().trim();
}
Liquibase liquibase = new Liquibase(changeLogFile, new CompositeFileOpener(antFO, fsFO), database);
liquibase.setCurrentDateTimeFunction(currentDateTimeFunction);
for (Map.Entry<String, Object> entry : changeLogProperties.entrySet()) {
liquibase.setChangeLogParameterValue(entry.getKey(), entry.getValue());
}
return liquibase;
}
protected Database createDatabaseObject(String driverClassName,
String databaseUrl,
String username,
String password,
String defaultSchemaName,
String databaseClass) throws Exception {
String[] strings = classpath.list();
final List<URL> taskClassPath = new ArrayList<URL>();
for (String string : strings) {
URL url = new File(string).toURL();
taskClassPath.add(url);
}
URLClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
public URLClassLoader run() {
return new URLClassLoader(taskClassPath.toArray(new URL[taskClassPath.size()]));
}
});
if (databaseUrl.startsWith("hibernate:")) {
return new HibernateDatabase(databaseUrl.substring("hibernate:".length()));
}
if (databaseClass != null) {
try
{
DatabaseFactory.getInstance().addDatabaseImplementation((Database) Class.forName(databaseClass, true, loader).newInstance());
}
catch (ClassCastException e) //fails in Ant in particular
{
DatabaseFactory.getInstance().addDatabaseImplementation((Database) Class.forName(databaseClass).newInstance());
}
}
if (driverClassName == null) {
driverClassName = DatabaseFactory.getInstance().findDefaultDriver(databaseUrl);
}
if (driverClassName == null) {
throw new JDBCException("driver not specified and no default could be found for "+databaseUrl);
}
Driver driver = (Driver) Class.forName(driverClassName, true, loader).newInstance();
Properties info = new Properties();
info.put("user", username);
info.put("password", password);
Connection connection = driver.connect(databaseUrl, info);
if (connection == null) {
throw new JDBCException("Connection could not be created to " + databaseUrl + " with driver " + driver.getClass().getName() + ". Possibly the wrong driver for the given database URL");
}
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
database.setDefaultSchemaName(defaultSchemaName);
return database;
}
public String getContexts() {
return contexts;
}
public void setContexts(String cntx) {
this.contexts = cntx;
}
/**
* Redirector of logs from java.util.logging to ANT's loggging
*/
protected static class LogRedirector {
private final Task task;
/**
* Constructor
*
* @param task
*/
protected LogRedirector(Task task) {
super();
this.task = task;
}
protected void redirectLogger() {
registerHandler(createHandler());
}
protected void registerHandler(Handler theHandler) {
Logger logger = LogFactory.getLogger();
for (Handler handler : logger.getHandlers()) {
logger.removeHandler(handler);
}
logger.addHandler(theHandler);
logger.setUseParentHandlers(false);
}
protected Handler createHandler() {
return new Handler() {
public void publish(LogRecord logRecord) {
task.log(logRecord.getMessage(), mapLevelToAntLevel(logRecord.getLevel()));
}
@Override
public void close() throws SecurityException {
}
@Override
public void flush() {
}
protected int mapLevelToAntLevel(Level level) {
if (Level.ALL == level) {
return Project.MSG_INFO;
} else if (Level.SEVERE == level) {
return Project.MSG_ERR;
} else if (Level.WARNING == level) {
return Project.MSG_WARN;
} else if (Level.INFO == level) {
return Project.MSG_INFO;
} else {
return Project.MSG_VERBOSE;
}
}
};
}
}
protected boolean shouldRun() {
String shouldRunProperty = System.getProperty(Liquibase.SHOULD_RUN_SYSTEM_PROPERTY);
if (shouldRunProperty != null && !Boolean.valueOf(shouldRunProperty)) {
log("LiquiBase did not run because '" + Liquibase.SHOULD_RUN_SYSTEM_PROPERTY + "' system property was set to false");
return false;
}
return true;
}
protected void closeDatabase(Liquibase liquibase) {
if (liquibase != null && liquibase.getDatabase() != null && liquibase.getDatabase().getConnection() != null) {
try {
liquibase.getDatabase().close();
} catch (JDBCException e) {
log("Error closing database: "+e.getMessage());
}
}
}
public String getDatabaseClass() {
return databaseClass;
}
public void setDatabaseClass(String databaseClass) {
this.databaseClass = databaseClass;
}
public static class ChangeLogProperty {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
| core/src/java/liquibase/ant/BaseLiquibaseTask.java | package liquibase.ant;
import liquibase.CompositeFileOpener;
import liquibase.FileOpener;
import liquibase.FileSystemFileOpener;
import liquibase.Liquibase;
import liquibase.util.LiquibaseUtil;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.HibernateDatabase;
import liquibase.exception.JDBCException;
import liquibase.log.LogFactory;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Reference;
import java.io.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.sql.Connection;
import java.sql.Driver;
import java.util.*;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* Base class for all Ant LiquiBase tasks. This class sets up LiquiBase and defines parameters
* that are common to all tasks.
*/
public class BaseLiquibaseTask extends Task {
private String changeLogFile;
private String driver;
private String url;
private String username;
private String password;
protected Path classpath;
private boolean promptOnNonLocalDatabase = false;
private String currentDateTimeFunction;
private String contexts;
private String outputFile;
private String defaultSchemaName;
private String databaseClass;
private Map<String, Object> changeLogProperties = new HashMap<String, Object>();
public BaseLiquibaseTask() {
super();
new LogRedirector(this).redirectLogger();
}
public boolean isPromptOnNonLocalDatabase() {
return promptOnNonLocalDatabase;
}
public void setPromptOnNonLocalDatabase(boolean promptOnNonLocalDatabase) {
this.promptOnNonLocalDatabase = promptOnNonLocalDatabase;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
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 getChangeLogFile() {
return changeLogFile;
}
public void setChangeLogFile(String changeLogFile) {
this.changeLogFile = changeLogFile;
}
public Path createClasspath() {
if (this.classpath == null) {
this.classpath = new Path(getProject());
}
return this.classpath.createPath();
}
public void setClasspathRef(Reference r) {
createClasspath().setRefid(r);
}
public String getCurrentDateTimeFunction() {
return currentDateTimeFunction;
}
public void setCurrentDateTimeFunction(String currentDateTimeFunction) {
this.currentDateTimeFunction = currentDateTimeFunction;
}
public String getOutputFile() {
return outputFile;
}
public void setOutputFile(String outputFile) {
this.outputFile = outputFile;
}
public Writer createOutputWriter() throws IOException {
if (outputFile == null) {
return null;
}
return new FileWriter(new File(getOutputFile()));
}
public PrintStream createPrintStream() throws IOException {
if (outputFile == null) {
return null;
}
return new PrintStream(new File(getOutputFile()));
}
public String getDefaultSchemaName() {
return defaultSchemaName;
}
public void setDefaultSchemaName(String defaultSchemaName) {
this.defaultSchemaName = defaultSchemaName;
}
public void addChangeLogProperty(ChangeLogProperty changeLogProperty) {
changeLogProperties.put(changeLogProperty.getName(), changeLogProperty.getValue());
}
protected Liquibase createLiquibase() throws Exception {
FileOpener antFO = new AntFileOpener(getProject(), classpath);
FileOpener fsFO = new FileSystemFileOpener();
Database database = createDatabaseObject(getDriver(), getUrl(), getUsername(), getPassword(), getDefaultSchemaName(),getDatabaseClass());
String changeLogFile = null;
if (getChangeLogFile() != null) {
changeLogFile = getChangeLogFile().trim();
}
Liquibase liquibase = new Liquibase(changeLogFile, new CompositeFileOpener(antFO, fsFO), database);
liquibase.setCurrentDateTimeFunction(currentDateTimeFunction);
for (Map.Entry<String, Object> entry : changeLogProperties.entrySet()) {
liquibase.setChangeLogParameterValue(entry.getKey(), entry.getValue());
}
return liquibase;
}
protected Database createDatabaseObject(String driverClassName,
String databaseUrl,
String username,
String password,
String defaultSchemaName,
String databaseClass) throws Exception {
String[] strings = classpath.list();
final List<URL> taskClassPath = new ArrayList<URL>();
for (String string : strings) {
URL url = new File(string).toURL();
taskClassPath.add(url);
}
URLClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
public URLClassLoader run() {
return new URLClassLoader(taskClassPath.toArray(new URL[taskClassPath.size()]));
}
});
if (databaseUrl.startsWith("hibernate:")) {
return new HibernateDatabase(databaseUrl.substring("hibernate:".length()));
}
if (databaseClass != null) {
try
{
DatabaseFactory.getInstance().addDatabaseImplementation((Database) Class.forName(databaseClass, true, loader).newInstance());
}
catch (ClassCastException e) //fails in Ant in particular
{
DatabaseFactory.getInstance().addDatabaseImplementation((Database) Class.forName(databaseClass).newInstance());
}
}
if (driverClassName == null) {
driverClassName = DatabaseFactory.getInstance().findDefaultDriver(databaseUrl);
}
if (driverClassName == null) {
throw new JDBCException("driver not specified and no default could be found for "+databaseUrl);
}
Driver driver = (Driver) Class.forName(driverClassName, true, loader).newInstance();
Properties info = new Properties();
info.put("user", username);
info.put("password", password);
Connection connection = driver.connect(databaseUrl, info);
if (connection == null) {
throw new JDBCException("Connection could not be created to " + databaseUrl + " with driver " + driver.getClass().getName() + ". Possibly the wrong driver for the given database URL");
}
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
database.setDefaultSchemaName(defaultSchemaName);
return database;
}
public String getContexts() {
return contexts;
}
public void setContexts(String cntx) {
this.contexts = cntx;
}
/**
* Redirector of logs from java.util.logging to ANT's loggging
*/
protected static class LogRedirector {
private final Task task;
/**
* Constructor
*
* @param task
*/
protected LogRedirector(Task task) {
super();
this.task = task;
}
protected void redirectLogger() {
registerHandler(createHandler());
}
protected void registerHandler(Handler theHandler) {
Logger logger = LogFactory.getLogger();
for (Handler handler : logger.getHandlers()) {
logger.removeHandler(handler);
}
logger.addHandler(theHandler);
logger.setUseParentHandlers(false);
}
protected Handler createHandler() {
return new Handler() {
public void publish(LogRecord logRecord) {
task.log(logRecord.getMessage(), mapLevelToAntLevel(logRecord.getLevel()));
}
@Override
public void close() throws SecurityException {
}
@Override
public void flush() {
}
protected int mapLevelToAntLevel(Level level) {
if (Level.ALL == level) {
return Project.MSG_INFO;
} else if (Level.SEVERE == level) {
return Project.MSG_ERR;
} else if (Level.WARNING == level) {
return Project.MSG_WARN;
} else if (Level.INFO == level) {
return Project.MSG_INFO;
} else {
return Project.MSG_VERBOSE;
}
}
};
}
}
protected boolean shouldRun() {
String shouldRunProperty = System.getProperty(Liquibase.SHOULD_RUN_SYSTEM_PROPERTY);
if (shouldRunProperty != null && !Boolean.valueOf(shouldRunProperty)) {
log("LiquiBase did not run because '" + Liquibase.SHOULD_RUN_SYSTEM_PROPERTY + "' system property was set to false");
return false;
}
return true;
}
protected void closeDatabase(Liquibase liquibase) {
if (liquibase != null && liquibase.getDatabase() != null && liquibase.getDatabase().getConnection() != null) {
try {
liquibase.getDatabase().close();
} catch (JDBCException e) {
log("Error closing database: "+e.getMessage());
}
}
}
public String getDatabaseClass() {
return databaseClass;
}
public void setDatabaseClass(String databaseClass) {
this.databaseClass = databaseClass;
}
public static class ChangeLogProperty {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
| 2212077 Ant task NPE on changeLogProperties (patch)
Applied patch
git-svn-id: a91d99a4c51940524e539abe295d6ea473345dd2@755 e6edf6fb-f266-4316-afb4-e53d95876a76
| core/src/java/liquibase/ant/BaseLiquibaseTask.java | 2212077 Ant task NPE on changeLogProperties (patch) Applied patch | <ide><path>ore/src/java/liquibase/ant/BaseLiquibaseTask.java
<ide> this.defaultSchemaName = defaultSchemaName;
<ide> }
<ide>
<del> public void addChangeLogProperty(ChangeLogProperty changeLogProperty) {
<add> public void addConfiguredChangeLogProperty(ChangeLogProperty changeLogProperty) {
<ide> changeLogProperties.put(changeLogProperty.getName(), changeLogProperty.getValue());
<ide> }
<ide>
<ide> return liquibase;
<ide> }
<ide>
<del> protected Database createDatabaseObject(String driverClassName,
<del> String databaseUrl,
<del> String username,
<del> String password,
<add> protected Database createDatabaseObject(String driverClassName,
<add> String databaseUrl,
<add> String username,
<add> String password,
<ide> String defaultSchemaName,
<ide> String databaseClass) throws Exception {
<ide> String[] strings = classpath.list();
<ide> return new HibernateDatabase(databaseUrl.substring("hibernate:".length()));
<ide> }
<ide>
<del> if (databaseClass != null) {
<del>
<add> if (databaseClass != null) {
<add>
<ide> try
<ide> {
<ide> DatabaseFactory.getInstance().addDatabaseImplementation((Database) Class.forName(databaseClass, true, loader).newInstance()); |
|
Java | apache-2.0 | 48aad1fd334e6f18675ce08cee589f3aef680e1a | 0 | real-logic/simple-binary-encoding,PKRoma/simple-binary-encoding,PKRoma/simple-binary-encoding,real-logic/simple-binary-encoding,PKRoma/simple-binary-encoding,PKRoma/simple-binary-encoding,PKRoma/simple-binary-encoding,real-logic/simple-binary-encoding,marksantos/simple-binary-encoding,real-logic/simple-binary-encoding,marksantos/simple-binary-encoding,real-logic/simple-binary-encoding,marksantos/simple-binary-encoding,marksantos/simple-binary-encoding,marksantos/simple-binary-encoding,PKRoma/simple-binary-encoding,PKRoma/simple-binary-encoding,real-logic/simple-binary-encoding,marksantos/simple-binary-encoding,marksantos/simple-binary-encoding,marksantos/simple-binary-encoding,real-logic/simple-binary-encoding | /* Copyright 2013-2017 Real Logic Ltd.
*
* 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 uk.co.real_logic.sbe.xml;
import uk.co.real_logic.sbe.PrimitiveType;
import uk.co.real_logic.sbe.PrimitiveValue;
import uk.co.real_logic.sbe.ir.Encoding;
import uk.co.real_logic.sbe.ir.Ir;
import uk.co.real_logic.sbe.ir.Signal;
import uk.co.real_logic.sbe.ir.Token;
import java.io.UnsupportedEncodingException;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
/**
* Class to hold the state while generating the {@link uk.co.real_logic.sbe.ir.Ir}.
*/
public class IrGenerator
{
private final List<Token> tokenList = new ArrayList<>();
private ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN;
/**
* Generate a complete {@link uk.co.real_logic.sbe.ir.Ir} for a given schema.
*
* @param schema from which the {@link uk.co.real_logic.sbe.ir.Ir} should be generated.
* @param namespace for the generated code.
* @return complete {@link uk.co.real_logic.sbe.ir.Ir} for a given schema.
*/
public Ir generate(final MessageSchema schema, final String namespace)
{
final List<Token> headerTokens = generateForHeader(schema);
final Ir ir = new Ir(
schema.packageName(),
namespace,
schema.id(),
schema.version(),
schema.semanticVersion(),
schema.byteOrder(),
headerTokens);
for (final Message message : schema.messages())
{
final long msgId = message.id();
ir.addMessage(msgId, generateForMessage(schema, msgId));
}
return ir;
}
/**
* Generate a complete {@link uk.co.real_logic.sbe.ir.Ir} for a given schema.
*
* @param schema from which the {@link uk.co.real_logic.sbe.ir.Ir} should be generated.
* @return complete {@link uk.co.real_logic.sbe.ir.Ir} for a given schema.
*/
public Ir generate(final MessageSchema schema)
{
return generate(schema, null);
}
private List<Token> generateForMessage(final MessageSchema schema, final long messageId)
{
tokenList.clear();
byteOrder = schema.byteOrder();
final Message msg = schema.getMessage(messageId);
addMessageSignal(msg, Signal.BEGIN_MESSAGE);
addAllFields(msg.fields());
addMessageSignal(msg, Signal.END_MESSAGE);
return tokenList;
}
private List<Token> generateForHeader(final MessageSchema schema)
{
tokenList.clear();
byteOrder = schema.byteOrder();
add(schema.messageHeader(), 0, null);
return tokenList;
}
private void addMessageSignal(final Message msg, final Signal signal)
{
final Token token = new Token.Builder()
.signal(signal)
.name(msg.name())
.description(msg.description())
.size(msg.blockLength())
.id(msg.id())
.version(msg.sinceVersion())
.deprecated(msg.deprecated())
.encoding(new Encoding.Builder()
.semanticType(msg.semanticType())
.build())
.build();
tokenList.add(token);
}
private void addFieldSignal(final Field field, final Signal signal)
{
final Encoding.Builder encodingBuilder = new Encoding.Builder()
.epoch(field.epoch())
.timeUnit(field.timeUnit())
.presence(mapPresence(field.presence()))
.semanticType(semanticTypeOf(null, field));
if (field.presence() == Presence.CONSTANT && null != field.valueRef())
{
final String valueRef = field.valueRef();
final byte[] bytes;
try
{
bytes = valueRef.getBytes("UTF-8");
}
catch (final UnsupportedEncodingException ex)
{
throw new RuntimeException(ex);
}
encodingBuilder.constValue(new PrimitiveValue(bytes, "UTF-8", valueRef.length()));
encodingBuilder.primitiveType(PrimitiveType.CHAR);
}
final Token token = new Token.Builder()
.signal(signal)
.size(field.computedBlockLength())
.name(field.name())
.description(field.description())
.id(field.id())
.offset(field.computedOffset())
.version(field.sinceVersion())
.deprecated(field.deprecated())
.encoding(encodingBuilder.build())
.build();
tokenList.add(token);
}
private void addAllFields(final List<Field> fieldList)
{
for (final Field field : fieldList)
{
final Type type = field.type();
if (type == null)
{
addFieldSignal(field, Signal.BEGIN_GROUP);
add(field.dimensionType(), 0, field);
addAllFields(field.groupFields());
addFieldSignal(field, Signal.END_GROUP);
}
else if (type instanceof CompositeType && field.isVariableLength())
{
addFieldSignal(field, Signal.BEGIN_VAR_DATA);
add((CompositeType)type, field.computedOffset(), field);
addFieldSignal(field, Signal.END_VAR_DATA);
}
else
{
addFieldSignal(field, Signal.BEGIN_FIELD);
if (type instanceof EncodedDataType)
{
add((EncodedDataType)type, field.computedOffset(), field);
}
else if (type instanceof CompositeType)
{
add((CompositeType)type, field.computedOffset(), field);
}
else if (type instanceof EnumType)
{
add((EnumType)type, field.computedOffset(), field);
}
else if (type instanceof SetType)
{
add((SetType)type, field.computedOffset(), field);
}
else
{
throw new IllegalStateException("Unknown type: " + type);
}
addFieldSignal(field, Signal.END_FIELD);
}
}
}
private void add(final CompositeType type, final int currOffset, final Field field)
{
final Token.Builder builder = new Token.Builder()
.signal(Signal.BEGIN_COMPOSITE)
.name(type.name())
.referencedName(type.referencedName())
.offset(currOffset)
.size(type.encodedLength())
.version(type.sinceVersion())
.deprecated(type.deprecated())
.description(type.description())
.encoding(new Encoding.Builder()
.semanticType(semanticTypeOf(type, field))
.build());
if (field != null)
{
builder.version(field.sinceVersion());
builder.deprecated(field.deprecated());
final String description = field.description();
if (null != description && description.length() > 0)
{
builder.description(description);
}
}
tokenList.add(builder.build());
int offset = 0;
for (final Type elementType : type.getTypeList())
{
if (elementType.offsetAttribute() != -1)
{
offset = elementType.offsetAttribute();
}
if (elementType instanceof EncodedDataType)
{
add((EncodedDataType)elementType, offset, null);
}
else if (elementType instanceof EnumType)
{
add((EnumType)elementType, offset, null);
}
else if (elementType instanceof SetType)
{
add((SetType)elementType, offset, null);
}
else if (elementType instanceof CompositeType)
{
add((CompositeType)elementType, offset, null);
}
offset += elementType.encodedLength();
}
tokenList.add(builder.signal(Signal.END_COMPOSITE).build());
}
private void add(final EnumType type, final int offset, final Field field)
{
final PrimitiveType encodingType = type.encodingType();
final Encoding.Builder encodingBuilder = new Encoding.Builder()
.primitiveType(encodingType)
.semanticType(semanticTypeOf(type, field))
.byteOrder(byteOrder);
if (type.presence() == Presence.OPTIONAL)
{
encodingBuilder.nullValue(encodingType.nullValue());
}
final Token.Builder builder = new Token.Builder()
.signal(Signal.BEGIN_ENUM)
.name(type.name())
.referencedName(type.referencedName())
.size(encodingType.size())
.offset(offset)
.version(type.sinceVersion())
.deprecated(type.deprecated())
.description(type.description())
.encoding(encodingBuilder.build());
if (field != null)
{
builder.version(field.sinceVersion());
builder.deprecated(field.deprecated());
final String description = field.description();
if (null != description && description.length() > 0)
{
builder.description(description);
}
}
tokenList.add(builder.build());
for (final EnumType.ValidValue validValue : type.validValues())
{
add(validValue, encodingType);
}
builder.signal(Signal.END_ENUM);
tokenList.add(builder.build());
}
private void add(final EnumType.ValidValue value, final PrimitiveType encodingType)
{
final Token.Builder builder = new Token.Builder()
.signal(Signal.VALID_VALUE)
.name(value.name())
.version(value.sinceVersion())
.deprecated(value.deprecated())
.description(value.description())
.encoding(new Encoding.Builder()
.byteOrder(byteOrder)
.primitiveType(encodingType)
.constValue(value.primitiveValue())
.build());
tokenList.add(builder.build());
}
private void add(final SetType type, final int offset, final Field field)
{
final PrimitiveType encodingType = type.encodingType();
final Token.Builder builder = new Token.Builder()
.signal(Signal.BEGIN_SET)
.name(type.name())
.referencedName(type.referencedName())
.size(encodingType.size())
.offset(offset)
.version(type.sinceVersion())
.deprecated(type.deprecated())
.description(type.description())
.encoding(new Encoding.Builder()
.semanticType(semanticTypeOf(type, field))
.primitiveType(encodingType)
.build());
if (field != null)
{
builder.version(field.sinceVersion());
builder.deprecated(field.deprecated());
final String description = field.description();
if (null != description && description.length() > 0)
{
builder.description(description);
}
}
tokenList.add(builder.build());
for (final SetType.Choice choice : type.choices())
{
add(choice, encodingType);
}
builder.signal(Signal.END_SET);
tokenList.add(builder.build());
}
private void add(final SetType.Choice value, final PrimitiveType encodingType)
{
final Token.Builder builder = new Token.Builder()
.signal(Signal.CHOICE)
.name(value.name())
.description(value.description())
.version(value.sinceVersion())
.deprecated(value.deprecated())
.encoding(new Encoding.Builder()
.constValue(value.primitiveValue())
.byteOrder(byteOrder)
.primitiveType(encodingType)
.build());
tokenList.add(builder.build());
}
private void add(final EncodedDataType type, final int offset, final Field field)
{
final Encoding.Builder encodingBuilder = new Encoding.Builder()
.primitiveType(type.primitiveType())
.byteOrder(byteOrder)
.semanticType(semanticTypeOf(type, field))
.characterEncoding(type.characterEncoding());
if (null != field)
{
encodingBuilder.epoch(field.epoch());
encodingBuilder.timeUnit(field.timeUnit());
}
final Token.Builder tokenBuilder = new Token.Builder()
.signal(Signal.ENCODING)
.name(type.name())
.referencedName(type.referencedName())
.size(type.encodedLength())
.description(type.description())
.version(type.sinceVersion())
.deprecated(type.deprecated())
.offset(offset);
if (field != null && !(field.type() instanceof CompositeType))
{
tokenBuilder.version(field.sinceVersion());
tokenBuilder.deprecated(field.deprecated());
final String description = field.description();
if (null != description && description.length() > 0)
{
tokenBuilder.description(description);
}
}
switch (type.presence())
{
case REQUIRED:
encodingBuilder
.presence(Encoding.Presence.REQUIRED)
.minValue(type.minValue())
.maxValue(type.maxValue());
break;
case OPTIONAL:
encodingBuilder
.presence(Encoding.Presence.OPTIONAL)
.minValue(type.minValue())
.maxValue(type.maxValue())
.nullValue(type.nullValue());
break;
case CONSTANT:
encodingBuilder
.presence(Encoding.Presence.CONSTANT)
.constValue(type.constVal());
break;
}
final Token token = tokenBuilder.encoding(encodingBuilder.build()).build();
tokenList.add(token);
}
private static String semanticTypeOf(final Type type, final Field field)
{
final String typeSemanticType = null != type ? type.semanticType() : null;
if (typeSemanticType != null)
{
return typeSemanticType;
}
return null != field ? field.semanticType() : null;
}
private Encoding.Presence mapPresence(final Presence presence)
{
Encoding.Presence encodingPresence = Encoding.Presence.REQUIRED;
if (null != presence)
{
switch (presence)
{
case OPTIONAL:
encodingPresence = Encoding.Presence.OPTIONAL;
break;
case CONSTANT:
encodingPresence = Encoding.Presence.CONSTANT;
break;
}
}
return encodingPresence;
}
} | sbe-tool/src/main/java/uk/co/real_logic/sbe/xml/IrGenerator.java | /* Copyright 2013-2017 Real Logic Ltd.
*
* 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 uk.co.real_logic.sbe.xml;
import uk.co.real_logic.sbe.PrimitiveType;
import uk.co.real_logic.sbe.PrimitiveValue;
import uk.co.real_logic.sbe.ir.Encoding;
import uk.co.real_logic.sbe.ir.Ir;
import uk.co.real_logic.sbe.ir.Signal;
import uk.co.real_logic.sbe.ir.Token;
import java.io.UnsupportedEncodingException;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
/**
* Class to hold the state while generating the {@link uk.co.real_logic.sbe.ir.Ir}.
*/
public class IrGenerator
{
private final List<Token> tokenList = new ArrayList<>();
private ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN;
/**
* Generate a complete {@link uk.co.real_logic.sbe.ir.Ir} for a given schema.
*
* @param schema from which the {@link uk.co.real_logic.sbe.ir.Ir} should be generated.
* @param namespace for the generated code.
* @return complete {@link uk.co.real_logic.sbe.ir.Ir} for a given schema.
*/
public Ir generate(final MessageSchema schema, final String namespace)
{
final List<Token> headerTokens = generateForHeader(schema);
final Ir ir = new Ir(
schema.packageName(),
namespace,
schema.id(),
schema.version(),
schema.semanticVersion(),
schema.byteOrder(),
headerTokens);
for (final Message message : schema.messages())
{
final long msgId = message.id();
ir.addMessage(msgId, generateForMessage(schema, msgId));
}
return ir;
}
/**
* Generate a complete {@link uk.co.real_logic.sbe.ir.Ir} for a given schema.
*
* @param schema from which the {@link uk.co.real_logic.sbe.ir.Ir} should be generated.
* @return complete {@link uk.co.real_logic.sbe.ir.Ir} for a given schema.
*/
public Ir generate(final MessageSchema schema)
{
return generate(schema, null);
}
private List<Token> generateForMessage(final MessageSchema schema, final long messageId)
{
tokenList.clear();
byteOrder = schema.byteOrder();
final Message msg = schema.getMessage(messageId);
addMessageSignal(msg, Signal.BEGIN_MESSAGE);
addAllFields(msg.fields());
addMessageSignal(msg, Signal.END_MESSAGE);
return tokenList;
}
private List<Token> generateForHeader(final MessageSchema schema)
{
tokenList.clear();
byteOrder = schema.byteOrder();
add(schema.messageHeader(), 0, null);
return tokenList;
}
private void addMessageSignal(final Message msg, final Signal signal)
{
final Token token = new Token.Builder()
.signal(signal)
.name(msg.name())
.description(msg.description())
.size(msg.blockLength())
.id(msg.id())
.version(msg.sinceVersion())
.deprecated(msg.deprecated())
.encoding(new Encoding.Builder()
.semanticType(msg.semanticType())
.build())
.build();
tokenList.add(token);
}
private void addFieldSignal(final Field field, final Signal signal)
{
final Encoding.Builder encodingBuilder = new Encoding.Builder()
.epoch(field.epoch())
.timeUnit(field.timeUnit())
.presence(mapPresence(field.presence()))
.semanticType(semanticTypeOf(null, field));
if (field.presence() == Presence.CONSTANT && null != field.valueRef())
{
final String valueRef = field.valueRef();
final byte[] bytes;
try
{
bytes = valueRef.getBytes("UTF-8");
}
catch (final UnsupportedEncodingException ex)
{
throw new RuntimeException(ex);
}
encodingBuilder.constValue(new PrimitiveValue(bytes, "UTF-8", valueRef.length()));
encodingBuilder.primitiveType(PrimitiveType.CHAR);
}
final Token token = new Token.Builder()
.signal(signal)
.size(field.computedBlockLength())
.name(field.name())
.description(field.description())
.id(field.id())
.offset(field.computedOffset())
.version(field.sinceVersion())
.deprecated(field.deprecated())
.encoding(encodingBuilder.build())
.build();
tokenList.add(token);
}
private void addAllFields(final List<Field> fieldList)
{
for (final Field field : fieldList)
{
final Type type = field.type();
if (type == null)
{
addFieldSignal(field, Signal.BEGIN_GROUP);
add(field.dimensionType(), 0, field);
addAllFields(field.groupFields());
addFieldSignal(field, Signal.END_GROUP);
}
else if (type instanceof CompositeType && field.isVariableLength())
{
addFieldSignal(field, Signal.BEGIN_VAR_DATA);
add((CompositeType)type, field.computedOffset(), field);
addFieldSignal(field, Signal.END_VAR_DATA);
}
else
{
addFieldSignal(field, Signal.BEGIN_FIELD);
if (type instanceof EncodedDataType)
{
add((EncodedDataType)type, field.computedOffset(), field);
}
else if (type instanceof CompositeType)
{
add((CompositeType)type, field.computedOffset(), field);
}
else if (type instanceof EnumType)
{
add((EnumType)type, field.computedOffset(), field);
}
else if (type instanceof SetType)
{
add((SetType)type, field.computedOffset(), field);
}
else
{
throw new IllegalStateException("Unknown type: " + type);
}
addFieldSignal(field, Signal.END_FIELD);
}
}
}
private void add(final CompositeType type, final int currOffset, final Field field)
{
final Token.Builder builder = new Token.Builder()
.signal(Signal.BEGIN_COMPOSITE)
.name(type.name())
.referencedName(type.referencedName())
.offset(currOffset)
.size(type.encodedLength())
.version(type.sinceVersion())
.deprecated(type.deprecated())
.description(type.description())
.encoding(new Encoding.Builder()
.semanticType(semanticTypeOf(type, field))
.build());
if (field != null)
{
builder.version(field.sinceVersion());
builder.deprecated(field.deprecated());
builder.description(field.description());
}
tokenList.add(builder.build());
int offset = 0;
for (final Type elementType : type.getTypeList())
{
if (elementType.offsetAttribute() != -1)
{
offset = elementType.offsetAttribute();
}
if (elementType instanceof EncodedDataType)
{
add((EncodedDataType)elementType, offset, null);
}
else if (elementType instanceof EnumType)
{
add((EnumType)elementType, offset, null);
}
else if (elementType instanceof SetType)
{
add((SetType)elementType, offset, null);
}
else if (elementType instanceof CompositeType)
{
add((CompositeType)elementType, offset, null);
}
offset += elementType.encodedLength();
}
tokenList.add(builder.signal(Signal.END_COMPOSITE).build());
}
private void add(final EnumType type, final int offset, final Field field)
{
final PrimitiveType encodingType = type.encodingType();
final Encoding.Builder encodingBuilder = new Encoding.Builder()
.primitiveType(encodingType)
.semanticType(semanticTypeOf(type, field))
.byteOrder(byteOrder);
if (type.presence() == Presence.OPTIONAL)
{
encodingBuilder.nullValue(encodingType.nullValue());
}
final Token.Builder builder = new Token.Builder()
.signal(Signal.BEGIN_ENUM)
.name(type.name())
.referencedName(type.referencedName())
.size(encodingType.size())
.offset(offset)
.version(type.sinceVersion())
.deprecated(type.deprecated())
.description(type.description())
.encoding(encodingBuilder.build());
if (field != null)
{
builder.version(field.sinceVersion());
builder.deprecated(field.deprecated());
builder.description(field.description());
}
tokenList.add(builder.build());
for (final EnumType.ValidValue validValue : type.validValues())
{
add(validValue, encodingType);
}
builder.signal(Signal.END_ENUM);
tokenList.add(builder.build());
}
private void add(final EnumType.ValidValue value, final PrimitiveType encodingType)
{
final Token.Builder builder = new Token.Builder()
.signal(Signal.VALID_VALUE)
.name(value.name())
.version(value.sinceVersion())
.deprecated(value.deprecated())
.description(value.description())
.encoding(new Encoding.Builder()
.byteOrder(byteOrder)
.primitiveType(encodingType)
.constValue(value.primitiveValue())
.build());
tokenList.add(builder.build());
}
private void add(final SetType type, final int offset, final Field field)
{
final PrimitiveType encodingType = type.encodingType();
final Token.Builder builder = new Token.Builder()
.signal(Signal.BEGIN_SET)
.name(type.name())
.referencedName(type.referencedName())
.size(encodingType.size())
.offset(offset)
.version(type.sinceVersion())
.deprecated(type.deprecated())
.description(type.description())
.encoding(new Encoding.Builder()
.semanticType(semanticTypeOf(type, field))
.primitiveType(encodingType)
.build());
if (field != null)
{
builder.version(field.sinceVersion());
builder.deprecated(field.deprecated());
builder.description(field.description());
}
tokenList.add(builder.build());
for (final SetType.Choice choice : type.choices())
{
add(choice, encodingType);
}
builder.signal(Signal.END_SET);
tokenList.add(builder.build());
}
private void add(final SetType.Choice value, final PrimitiveType encodingType)
{
final Token.Builder builder = new Token.Builder()
.signal(Signal.CHOICE)
.name(value.name())
.description(value.description())
.version(value.sinceVersion())
.deprecated(value.deprecated())
.encoding(new Encoding.Builder()
.constValue(value.primitiveValue())
.byteOrder(byteOrder)
.primitiveType(encodingType)
.build());
tokenList.add(builder.build());
}
private void add(final EncodedDataType type, final int offset, final Field field)
{
final Encoding.Builder encodingBuilder = new Encoding.Builder()
.primitiveType(type.primitiveType())
.byteOrder(byteOrder)
.semanticType(semanticTypeOf(type, field))
.characterEncoding(type.characterEncoding());
if (null != field)
{
encodingBuilder.epoch(field.epoch());
encodingBuilder.timeUnit(field.timeUnit());
}
final Token.Builder tokenBuilder = new Token.Builder()
.signal(Signal.ENCODING)
.name(type.name())
.referencedName(type.referencedName())
.size(type.encodedLength())
.description(type.description())
.version(type.sinceVersion())
.deprecated(type.deprecated())
.offset(offset);
if (field != null && !(field.type() instanceof CompositeType))
{
tokenBuilder.version(field.sinceVersion());
tokenBuilder.deprecated(field.deprecated());
tokenBuilder.description(field.description());
}
switch (type.presence())
{
case REQUIRED:
encodingBuilder
.presence(Encoding.Presence.REQUIRED)
.minValue(type.minValue())
.maxValue(type.maxValue());
break;
case OPTIONAL:
encodingBuilder
.presence(Encoding.Presence.OPTIONAL)
.minValue(type.minValue())
.maxValue(type.maxValue())
.nullValue(type.nullValue());
break;
case CONSTANT:
encodingBuilder
.presence(Encoding.Presence.CONSTANT)
.constValue(type.constVal());
break;
}
final Token token = tokenBuilder.encoding(encodingBuilder.build()).build();
tokenList.add(token);
}
private static String semanticTypeOf(final Type type, final Field field)
{
final String typeSemanticType = null != type ? type.semanticType() : null;
if (typeSemanticType != null)
{
return typeSemanticType;
}
return null != field ? field.semanticType() : null;
}
private Encoding.Presence mapPresence(final Presence presence)
{
Encoding.Presence encodingPresence = Encoding.Presence.REQUIRED;
if (null != presence)
{
switch (presence)
{
case OPTIONAL:
encodingPresence = Encoding.Presence.OPTIONAL;
break;
case CONSTANT:
encodingPresence = Encoding.Presence.CONSTANT;
break;
}
}
return encodingPresence;
}
} | [Java] Override description of type on field only if field has a description.
| sbe-tool/src/main/java/uk/co/real_logic/sbe/xml/IrGenerator.java | [Java] Override description of type on field only if field has a description. | <ide><path>be-tool/src/main/java/uk/co/real_logic/sbe/xml/IrGenerator.java
<ide> {
<ide> builder.version(field.sinceVersion());
<ide> builder.deprecated(field.deprecated());
<del> builder.description(field.description());
<add>
<add> final String description = field.description();
<add> if (null != description && description.length() > 0)
<add> {
<add> builder.description(description);
<add> }
<ide> }
<ide>
<ide> tokenList.add(builder.build());
<ide> {
<ide> builder.version(field.sinceVersion());
<ide> builder.deprecated(field.deprecated());
<del> builder.description(field.description());
<add>
<add> final String description = field.description();
<add> if (null != description && description.length() > 0)
<add> {
<add> builder.description(description);
<add> }
<ide> }
<ide>
<ide> tokenList.add(builder.build());
<ide> {
<ide> builder.version(field.sinceVersion());
<ide> builder.deprecated(field.deprecated());
<del> builder.description(field.description());
<add>
<add> final String description = field.description();
<add> if (null != description && description.length() > 0)
<add> {
<add> builder.description(description);
<add> }
<ide> }
<ide>
<ide> tokenList.add(builder.build());
<ide> {
<ide> tokenBuilder.version(field.sinceVersion());
<ide> tokenBuilder.deprecated(field.deprecated());
<del> tokenBuilder.description(field.description());
<add>
<add> final String description = field.description();
<add> if (null != description && description.length() > 0)
<add> {
<add> tokenBuilder.description(description);
<add> }
<ide> }
<ide>
<ide> switch (type.presence()) |
|
JavaScript | apache-2.0 | 98d628ee3e8771c9a6384b91948509dbcb6e7ca6 | 0 | pairyo/pdf.js,tinderboxhq/pdf.js,Lhuihui/pdf.js,fkaelberer/pdf.js,Datacom/pdf.js,tinderboxhq/pdf.js,mysterlune/pdf.js,vivin/pdf.js,mbbaig/pdf.js,luiseduardohdbackup/pdf.js,brendandahl/pdf.js,kalley/pdf.js,Ricardh522/pdf.js,Ju2ender/pdf.js,Mendeley/pdf.js,happybelly/pdf.js,iamkhush/pdf.js,nawawi/pdf.js,CodingFabian/pdf.js,Ricardh522/pdf.js,Thunderforge/pdf.js,sdmbuild/pdf.js,ebsco/pdf.js,EvilTrev/pdf.js,mukulmishra18/pdf.js,bobwol/pdf.js,youprofit/pdf.js,Ju2ender/pdf.js,yp2/pdf.js,mainegreen/pdf.js,maragh/pdf.js,eddyzhuo/pdf.js,douglasvegas/pdf.js,selique/pdf.js,CodingFabian/pdf.js,WoundCentrics/pdf.js,joelkuiper/pdf.js,timvandermeij/pdf.js,shaowei-su/pdf.js,Thunderforge/pdf.js,xialei/pdf.js,mozilla/pdf.js,MASmedios/pdf.js,DavidPrevot/pdf.js,viveksjain/pdf.js,MultivitaminLLC/pdf.js,Rob--W/pdf.js,selique/pdf.js,pramodhkp/pdf.js-gsoc-2014,Snuffleupagus/pdf.js,barrytielkes/pdf.js,macroplant/pdf.js,fashionsun/pdf.js,fkaelberer/pdf.js,jokamjohn/pdf.js,erikdejonge/pdf.js,Mendeley/pdf.js,adlerweb/pdf.js-Touch,gorcz/pdf.js,KlausRaynor/pdf.js,lentan1029/pdf.js,yuriyua/pdf.js,gigaga/pdf.js,ydfzgyj/pdf.js,ebsco/pdf.js,parthiban019/pdf.js,yp2/pdf.js,elcorders/pdf.js,zhaosichao/pdf.js,Snuffleupagus/pdf.js,WoundCentrics/pdf.js,Lhuihui/pdf.js,ajrulez/pdf.js,wuhuizuo/pdf.js,sitexa/pdf.js,ajrulez/pdf.js,gorcz/pdf.js,jlegewie/pdf.js,xavier114fch/pdf.js,anoopelias/pdf.js,microcom/pdf.js,barrytielkes/pdf.js,nawawi/pdf.js,kalley/pdf.js,ebsco/pdf.js,deenjohn/pdf.js,existentialism/pdf.js,parthiban019/pdf.js,elcorders/pdf.js,sdmbuild/pdf.js,elcorders/pdf.js,ajrulez/pdf.js,WoundCentrics/pdf.js,ShotaArai/gwitsch-pdf.js,savinn/pdf.js,Dawnflying/pdf.js,barrytielkes/pdf.js,maragh/pdf.js,mweimerskirch/pdf.js,xpati/pdf.js,harshavardhana/pdf.js,Mendeley/pdf.js,shaowei-su/pdf.js,zwily/pdf.js,joelkuiper/pdf.js,Shoobx/pdf.js,redanium/pdf.js,tmarrinan/pdf.js,yuriyua/pdf.js,allenmo/pdf.js,MASmedios/pdf.js,existentialism/pdf.js,MASmedios/pdf.js,showpad/mozilla-pdf.js,erikdejonge/pdf.js,redanium/pdf.js,JasonMPE/pdf.js,jazzy-em/pdf.js,showpad/mozilla-pdf.js,viveksjain/pdf.js,humphd/pdf.js,Mendeley/pdf.js,ynteng/pdf.js,mcanthony/pdf.js,pairyo/pdf.js,Lhuihui/pdf.js,ShiYw/pdf.js,bobwol/pdf.js,THausherr/pdf.js,fashionsun/pdf.js,petercpg/pdf.js,caremerge/pdf.js,mauricionr/pdf.js,happybelly/pdf.js,parthiban019/pdf.js,mcanthony/pdf.js,Ju2ender/pdf.js,timvandermeij/pdf.js,savinn/pdf.js,xpati/pdf.js,ynteng/pdf.js,pairyo/pdf.js,eddyzhuo/pdf.js,sunilomrey/pdf.js,mauricionr/pdf.js,mozilla/pdf.js,sdmbuild/pdf.js,maragh/pdf.js,joelkuiper/pdf.js,jokamjohn/pdf.js,mozilla/pdf.js,zwily/pdf.js,KamiHQ/pdf.js,JasonMPE/pdf.js,redanium/pdf.js,Ju2ender/pdf.js,THausherr/pdf.js,zhaosichao/pdf.js,fashionsun/pdf.js,Flekyno/pdfjs,DORNINEM/pdf.js,Snuffleupagus/pdf.js,KlausRaynor/pdf.js,deenjohn/pdf.js,douglasvegas/pdf.js,reggersusa/pdf.js,bobwol/pdf.js,jibaro/pdf.js,ynteng/pdf.js,mmaroti/pdf.js,erikdejonge/pdf.js,Datacom/pdf.js,petercpg/pdf.js,gmcdowell/pdf.js,zhaosichao/pdf.js,CodingFabian/pdf.js,WhitesteinTechnologies/wt-vaadin-pdf.js,NitroLabs/pdf.js,yurydelendik/pdf.js,redanium/pdf.js,shaowei-su/pdf.js,declara/pdf.js,yp2/pdf.js,fashionsun/pdf.js,haojiejie/pdf.js,reggersusa/pdf.js,HongwuLin/Pdf.js,Thunderforge/pdf.js,gmcdowell/pdf.js,mdamt/pdf.js,pairyo/pdf.js,happybelly/pdf.js,xialei/pdf.js,Workiva/pdf.js,HongwuLin/Pdf.js,nkpgardose/pdf.js,luiseduardohdbackup/pdf.js,Lhuihui/pdf.js,xpati/pdf.js,xpati/pdf.js,savinn/pdf.js,mcanthony/pdf.js,HongwuLin/Pdf.js,mmaroti/pdf.js,redanium/pdf.js,MultivitaminLLC/pdf.js,mweimerskirch/pdf.js,dannydes/WebSeniorReader,allenmo/pdf.js,barrytielkes/pdf.js,declara/pdf.js,thejdeep/pdf.js,ydfzgyj/pdf.js,viveksjain/pdf.js,sdmbuild/pdf.js,zhaosichao/pdf.js,nkpgardose/pdf.js,Ricardh522/pdf.js,savinn/pdf.js,calexandrepcjr/pdf.js,douglasvegas/pdf.js,gmcdowell/pdf.js,HongwuLin/Pdf.js,drosi94/pdf.js,mmaroti/pdf.js,ebsco/pdf.js,skalnik/pdf.js,sitexa/pdf.js,luiseduardohdbackup/pdf.js,ShotaArai/gwitsch-pdf.js,douglasvegas/pdf.js,ebsco/pdf.js,nirdoshyadav/pdf.js,jasonjensen/pdf.js,zwily/pdf.js,DavidPrevot/pdf.js,a0preetham/pdf.js,mbbaig/pdf.js,happybelly/pdf.js,gmcdowell/pdf.js,bhanu475/pdf.js,Thunderforge/pdf.js,calexandrepcjr/pdf.js,ynteng/pdf.js,DavidPrevot/pdf.js,sunilomrey/pdf.js,Mendeley/pdf.js,lentan1029/pdf.js,sunilomrey/pdf.js,reggersusa/pdf.js,Workiva/pdf.js,parthiban019/pdf.js,petercpg/pdf.js,ynteng/pdf.js,sitexa/pdf.js,KlausRaynor/pdf.js,Datacom/pdf.js,calexandrepcjr/pdf.js,1and1/pdf.js,yp2/pdf.js,shaowei-su/pdf.js,bobwol/pdf.js,allenmo/pdf.js,bh213/pdf.js,kalley/pdf.js,mauricionr/pdf.js,Lhuihui/pdf.js,erikdejonge/pdf.js,KamiHQ/pdf.js,showpad/mozilla-pdf.js,ShiYw/pdf.js,selique/pdf.js,EvilTrev/pdf.js,Ricardh522/pdf.js,haojiejie/pdf.js,xavier114fch/pdf.js,DORNINEM/pdf.js,deenjohn/pdf.js,mbbaig/pdf.js,mdamt/pdf.js,DORNINEM/pdf.js,tmarrinan/pdf.js,1and1/pdf.js,mdamt/pdf.js,Flekyno/pdfjs,douglasvegas/pdf.js,bhanu475/pdf.js,GPHemsley/pdf.js,GPHemsley/pdf.js,nkpgardose/pdf.js,macroplant/pdf.js,jokamjohn/pdf.js,Flipkart/pdf.js,dirkliu/pdf.js,erikdejonge/pdf.js,mdamt/pdf.js,KlausRaynor/pdf.js,msarti/pdf.js,zhaosichao/pdf.js,ShiYw/pdf.js,mdamt/pdf.js,Ricardh522/pdf.js,zwily/pdf.js,mweimerskirch/pdf.js,bhanu475/pdf.js,xialei/pdf.js,MASmedios/pdf.js,ShotaArai/gwitsch-pdf.js,WoundCentrics/pdf.js,sunilomrey/pdf.js,jibaro/pdf.js,tathata/pdf.js,dsprenkels/pdf.js,sitexa/pdf.js,viveksjain/pdf.js,sdmbuild/pdf.js,luiseduardohdbackup/pdf.js,gorcz/pdf.js,youprofit/pdf.js,Flekyno/pdfjs,NitroLabs/pdf.js,ShiYw/pdf.js,CodingFabian/pdf.js,allenmo/pdf.js,ajrulez/pdf.js,mukulmishra18/pdf.js,sdmbuild/pdf.js,brendandahl/pdf.js,mauricionr/pdf.js,websirnik/pdf.js,joelkuiper/pdf.js,existentialism/pdf.js,msarti/pdf.js,DORNINEM/pdf.js,microcom/pdf.js,wuhuizuo/pdf.js,datalanche/pdf.js,ShiYw/pdf.js,CodingFabian/pdf.js,Dawnflying/pdf.js,jibaro/pdf.js,nirdoshyadav/pdf.js,mainegreen/pdf.js,Dawnflying/pdf.js,Flipkart/pdf.js,JasonMPE/pdf.js,mcanthony/pdf.js,iesl/pdf.js,THausherr/pdf.js,Shoobx/pdf.js,maragh/pdf.js,wuhuizuo/pdf.js,jibaro/pdf.js,zyfran/pdf.js,youprofit/pdf.js,zyfran/pdf.js,reggersusa/pdf.js,gigaga/pdf.js,humphd/pdf.js,DavidPrevot/pdf.js,wuhuizuo/pdf.js,msarti/pdf.js,petercpg/pdf.js,skalnik/pdf.js,eddyzhuo/pdf.js,thepulkitagarwal/pdf.js,msarti/pdf.js,haojiejie/pdf.js,mmaroti/pdf.js,sunilomrey/pdf.js,Datacom/pdf.js,fashionsun/pdf.js,websirnik/pdf.js,bobwol/pdf.js,WoundCentrics/pdf.js,Ju2ender/pdf.js,NitroLabs/pdf.js,Thunderforge/pdf.js,humphd/pdf.js,mcanthony/pdf.js,adlerweb/pdf.js-Touch,OHIF/pdf.js,kalley/pdf.js,caremerge/pdf.js,bhanu475/pdf.js,elcorders/pdf.js,timvandermeij/pdf.js,calexandrepcjr/pdf.js,yuriyua/pdf.js,calexandrepcjr/pdf.js,barrytielkes/pdf.js,yp2/pdf.js,OHIF/pdf.js,NitroLabs/pdf.js,mysterlune/pdf.js,selique/pdf.js,JasonMPE/pdf.js,vivin/pdf.js,JasonMPE/pdf.js,dsprenkels/pdf.js,youprofit/pdf.js,msarti/pdf.js,vivin/pdf.js,zyfran/pdf.js,mauricionr/pdf.js,ShotaArai/gwitsch-pdf.js,xialei/pdf.js,mweimerskirch/pdf.js,zyfran/pdf.js,mweimerskirch/pdf.js,savinn/pdf.js,humphd/pdf.js,HongwuLin/Pdf.js,reggersusa/pdf.js,luiseduardohdbackup/pdf.js,viveksjain/pdf.js,jokamjohn/pdf.js,mmaroti/pdf.js,zyfran/pdf.js,ajrulez/pdf.js,nkpgardose/pdf.js,pairyo/pdf.js,yuriyua/pdf.js,macroplant/pdf.js,kalley/pdf.js,selique/pdf.js,maragh/pdf.js,bhanu475/pdf.js,jibaro/pdf.js,zwily/pdf.js,gmcdowell/pdf.js,nkpgardose/pdf.js,declara/pdf.js,operasoftware/pdf.js,THausherr/pdf.js,nawawi/pdf.js,allenmo/pdf.js,tmarrinan/pdf.js,jasonjensen/pdf.js,shaowei-su/pdf.js,KlausRaynor/pdf.js,DavidPrevot/pdf.js,THausherr/pdf.js,eddyzhuo/pdf.js,elcorders/pdf.js,bh213/pdf.js,MASmedios/pdf.js,erikdejonge/pdf.js,yurydelendik/pdf.js,wuhuizuo/pdf.js,dannydes/WebSeniorReader,joelkuiper/pdf.js,parthiban019/pdf.js,drosi94/pdf.js,happybelly/pdf.js,thepulkitagarwal/pdf.js,jokamjohn/pdf.js,humphd/pdf.js,yuriyua/pdf.js,iamkhush/pdf.js,haojiejie/pdf.js,dirkliu/pdf.js,youprofit/pdf.js,Rob--W/pdf.js,iesl/pdf.js,sitexa/pdf.js,Shoobx/pdf.js,DORNINEM/pdf.js,ShotaArai/gwitsch-pdf.js,deenjohn/pdf.js,Dawnflying/pdf.js,eddyzhuo/pdf.js,jazzy-em/pdf.js,ShotaArai/gwitsch-pdf.js,WhitesteinTechnologies/wt-vaadin-pdf.js,reggersusa/pdf.js,datalanche/pdf.js,anoopelias/pdf.js,Datacom/pdf.js,deenjohn/pdf.js,haojiejie/pdf.js,a0preetham/pdf.js,xialei/pdf.js,Dawnflying/pdf.js,tathata/pdf.js,dirkliu/pdf.js,petercpg/pdf.js,xpati/pdf.js | /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
var isWorker = (typeof window == 'undefined');
/**
* Maximum file size of the font.
*/
var kMaxFontFileSize = 300000;
/**
* Maximum time to wait for a font to be loaded by font-face rules.
*/
var kMaxWaitForFontFace = 1000;
/**
* Hold a map of decoded fonts and of the standard fourteen Type1
* fonts and their acronyms.
*/
var stdFontMap = {
'Arial': 'Helvetica',
'Arial_Bold': 'Helvetica-Bold',
'Arial_BoldItalic': 'Helvetica-BoldOblique',
'Arial_Italic': 'Helvetica-Oblique',
'Arial_BoldItalicMT': 'Helvetica-BoldOblique',
'Arial_BoldMT': 'Helvetica-Bold',
'Arial_ItalicMT': 'Helvetica-Oblique',
'ArialMT': 'Helvetica',
'Courier_Bold': 'Courier-Bold',
'Courier_BoldItalic': 'Courier-BoldOblique',
'Courier_Italic': 'Courier-Oblique',
'CourierNew': 'Courier',
'CourierNew_Bold': 'Courier-Bold',
'CourierNew_BoldItalic': 'Courier-BoldOblique',
'CourierNew_Italic': 'Courier-Oblique',
'CourierNewPS_BoldItalicMT': 'Courier-BoldOblique',
'CourierNewPS_BoldMT': 'Courier-Bold',
'CourierNewPS_ItalicMT': 'Courier-Oblique',
'CourierNewPSMT': 'Courier',
'Helvetica_Bold': 'Helvetica-Bold',
'Helvetica_BoldItalic': 'Helvetica-BoldOblique',
'Helvetica_Italic': 'Helvetica-Oblique',
'Symbol_Bold': 'Symbol',
'Symbol_BoldItalic': 'Symbol',
'Symbol_Italic': 'Symbol',
'TimesNewRoman': 'Times-Roman',
'TimesNewRoman_Bold': 'Times-Bold',
'TimesNewRoman_BoldItalic': 'Times-BoldItalic',
'TimesNewRoman_Italic': 'Times-Italic',
'TimesNewRomanPS': 'Times-Roman',
'TimesNewRomanPS_Bold': 'Times-Bold',
'TimesNewRomanPS_BoldItalic': 'Times-BoldItalic',
'TimesNewRomanPS_BoldItalicMT': 'Times-BoldItalic',
'TimesNewRomanPS_BoldMT': 'Times-Bold',
'TimesNewRomanPS_Italic': 'Times-Italic',
'TimesNewRomanPS_ItalicMT': 'Times-Italic',
'TimesNewRomanPSMT': 'Times-Roman',
'TimesNewRomanPSMT_Bold': 'Times-Bold',
'TimesNewRomanPSMT_BoldItalic': 'Times-BoldItalic',
'TimesNewRomanPSMT_Italic': 'Times-Italic'
};
var FontMeasure = (function FontMeasure() {
var kScalePrecision = 50;
var ctx = document.createElement('canvas').getContext('2d');
ctx.scale(1 / kScalePrecision, 1);
var current;
var measureCache;
return {
setActive: function fonts_setActive(font, size) {
if (current = font) {
var sizes = current.sizes;
if (!(measureCache = sizes[size]))
measureCache = sizes[size] = Object.create(null);
} else {
measureCache = null;
}
var name = font.loadedName;
var bold = font.bold ? 'bold' : 'normal';
var italic = font.italic ? 'italic' : 'normal';
size *= kScalePrecision;
var rule = italic + ' ' + bold + ' ' + size + 'px "' + name + '"';
ctx.font = rule;
},
measureText: function fonts_measureText(text) {
var width;
if (measureCache && (width = measureCache[text]))
return width;
width = ctx.measureText(text).width / kScalePrecision;
if (measureCache)
measureCache[text] = width;
return width;
}
};
})();
var FontLoader = {
listeningForFontLoad: false,
bind: function(fonts, callback) {
function checkFontsLoaded() {
for (var i = 0; i < objs.length; i++) {
var fontObj = objs[i];
if (fontObj.loading) {
return false;
}
}
document.documentElement.removeEventListener(
'pdfjsFontLoad', checkFontsLoaded, false);
callback();
return true;
}
var rules = [], names = [], objs = [];
for (var i = 0; i < fonts.length; i++) {
var font = fonts[i];
var obj = new Font(font.name, font.file, font.properties);
objs.push(obj);
var str = '';
var data = obj.data;
if (data) {
var length = data.length;
for (var j = 0; j < length; j++)
str += String.fromCharCode(data[j]);
var rule = isWorker ? obj.bindWorker(str) : obj.bindDOM(str);
if (rule) {
rules.push(rule);
names.push(obj.loadedName);
}
}
}
this.listeningForFontLoad = false;
if (!isWorker && rules.length) {
FontLoader.prepareFontLoadEvent(rules, names, objs);
}
if (!checkFontsLoaded()) {
document.documentElement.addEventListener(
'pdfjsFontLoad', checkFontsLoaded, false);
}
return objs;
},
// Set things up so that at least one pdfjsFontLoad event is
// dispatched when all the @font-face |rules| for |names| have been
// loaded in a subdocument. It's expected that the load of |rules|
// has already started in this (outer) document, so that they should
// be ordered before the load in the subdocument.
prepareFontLoadEvent: function(rules, names, objs) {
/** Hack begin */
// There's no event when a font has finished downloading so the
// following code is a dirty hack to 'guess' when a font is
// ready. This code will be obsoleted by Mozilla bug 471915.
//
// The only reliable way to know if a font is loaded in Gecko
// (at the moment) is document.onload in a document with
// a @font-face rule defined in a "static" stylesheet. We use a
// subdocument in an <iframe>, set up properly, to know when
// our @font-face rule was loaded. However, the subdocument and
// outer document can't share CSS rules, so the inner document
// is only part of the puzzle. The second piece is an invisible
// div created in order to force loading of the @font-face in
// the *outer* document. (The font still needs to be loaded for
// its metrics, for reflow). We create the div first for the
// outer document, then create the iframe. Unless something
// goes really wonkily, we expect the @font-face for the outer
// document to be processed before the inner. That's still
// fragile, but seems to work in practice.
//
// The postMessage() hackery was added to work around chrome bug
// 82402.
var div = document.createElement('div');
div.setAttribute('style',
'visibility: hidden;' +
'width: 10px; height: 10px;' +
'position: absolute; top: 0px; left: 0px;');
var html = '';
for (var i = 0; i < names.length; ++i) {
html += '<span style="font-family:' + names[i] + '">Hi</span>';
}
div.innerHTML = html;
document.body.appendChild(div);
if (!this.listeningForFontLoad) {
window.addEventListener(
'message',
function(e) {
var fontNames = JSON.parse(e.data);
for (var i = 0; i < objs.length; ++i) {
var font = objs[i];
font.loading = false;
}
var evt = document.createEvent('Events');
evt.initEvent('pdfjsFontLoad', true, false);
document.documentElement.dispatchEvent(evt);
},
false);
this.listeningForFontLoad = true;
}
// XXX we should have a time-out here too, and maybe fire
// pdfjsFontLoadFailed?
var src = '<!DOCTYPE HTML><html><head>';
src += '<style type="text/css">';
for (var i = 0; i < rules.length; ++i) {
src += rules[i];
}
src += '</style>';
src += '<script type="application/javascript">';
var fontNamesArray = '';
for (var i = 0; i < names.length; ++i) {
fontNamesArray += '"' + names[i] + '", ';
}
src += ' var fontNames=[' + fontNamesArray + '];\n';
src += ' window.onload = function () {\n';
src += ' top.postMessage(JSON.stringify(fontNames), "*");\n';
src += ' }';
src += '</script></head><body>';
for (var i = 0; i < names.length; ++i) {
src += '<p style="font-family:\'' + names[i] + '\'">Hi</p>';
}
src += '</body></html>';
var frame = document.createElement('iframe');
frame.src = 'data:text/html,' + src;
frame.setAttribute('style',
'visibility: hidden;' +
'width: 10px; height: 10px;' +
'position: absolute; top: 0px; left: 0px;');
document.body.appendChild(frame);
/** Hack end */
}
};
var UnicodeRanges = [
{ 'begin': 0x0000, 'end': 0x007F }, // Basic Latin
{ 'begin': 0x0080, 'end': 0x00FF }, // Latin-1 Supplement
{ 'begin': 0x0100, 'end': 0x017F }, // Latin Extended-A
{ 'begin': 0x0180, 'end': 0x024F }, // Latin Extended-B
{ 'begin': 0x0250, 'end': 0x02AF }, // IPA Extensions
{ 'begin': 0x02B0, 'end': 0x02FF }, // Spacing Modifier Letters
{ 'begin': 0x0300, 'end': 0x036F }, // Combining Diacritical Marks
{ 'begin': 0x0370, 'end': 0x03FF }, // Greek and Coptic
{ 'begin': 0x2C80, 'end': 0x2CFF }, // Coptic
{ 'begin': 0x0400, 'end': 0x04FF }, // Cyrillic
{ 'begin': 0x0530, 'end': 0x058F }, // Armenian
{ 'begin': 0x0590, 'end': 0x05FF }, // Hebrew
{ 'begin': 0xA500, 'end': 0xA63F }, // Vai
{ 'begin': 0x0600, 'end': 0x06FF }, // Arabic
{ 'begin': 0x07C0, 'end': 0x07FF }, // NKo
{ 'begin': 0x0900, 'end': 0x097F }, // Devanagari
{ 'begin': 0x0980, 'end': 0x09FF }, // Bengali
{ 'begin': 0x0A00, 'end': 0x0A7F }, // Gurmukhi
{ 'begin': 0x0A80, 'end': 0x0AFF }, // Gujarati
{ 'begin': 0x0B00, 'end': 0x0B7F }, // Oriya
{ 'begin': 0x0B80, 'end': 0x0BFF }, // Tamil
{ 'begin': 0x0C00, 'end': 0x0C7F }, // Telugu
{ 'begin': 0x0C80, 'end': 0x0CFF }, // Kannada
{ 'begin': 0x0D00, 'end': 0x0D7F }, // Malayalam
{ 'begin': 0x0E00, 'end': 0x0E7F }, // Thai
{ 'begin': 0x0E80, 'end': 0x0EFF }, // Lao
{ 'begin': 0x10A0, 'end': 0x10FF }, // Georgian
{ 'begin': 0x1B00, 'end': 0x1B7F }, // Balinese
{ 'begin': 0x1100, 'end': 0x11FF }, // Hangul Jamo
{ 'begin': 0x1E00, 'end': 0x1EFF }, // Latin Extended Additional
{ 'begin': 0x1F00, 'end': 0x1FFF }, // Greek Extended
{ 'begin': 0x2000, 'end': 0x206F }, // General Punctuation
{ 'begin': 0x2070, 'end': 0x209F }, // Superscripts And Subscripts
{ 'begin': 0x20A0, 'end': 0x20CF }, // Currency Symbol
{ 'begin': 0x20D0, 'end': 0x20FF }, // Combining Diacritical Marks For Symbols
{ 'begin': 0x2100, 'end': 0x214F }, // Letterlike Symbols
{ 'begin': 0x2150, 'end': 0x218F }, // Number Forms
{ 'begin': 0x2190, 'end': 0x21FF }, // Arrows
{ 'begin': 0x2200, 'end': 0x22FF }, // Mathematical Operators
{ 'begin': 0x2300, 'end': 0x23FF }, // Miscellaneous Technical
{ 'begin': 0x2400, 'end': 0x243F }, // Control Pictures
{ 'begin': 0x2440, 'end': 0x245F }, // Optical Character Recognition
{ 'begin': 0x2460, 'end': 0x24FF }, // Enclosed Alphanumerics
{ 'begin': 0x2500, 'end': 0x257F }, // Box Drawing
{ 'begin': 0x2580, 'end': 0x259F }, // Block Elements
{ 'begin': 0x25A0, 'end': 0x25FF }, // Geometric Shapes
{ 'begin': 0x2600, 'end': 0x26FF }, // Miscellaneous Symbols
{ 'begin': 0x2700, 'end': 0x27BF }, // Dingbats
{ 'begin': 0x3000, 'end': 0x303F }, // CJK Symbols And Punctuation
{ 'begin': 0x3040, 'end': 0x309F }, // Hiragana
{ 'begin': 0x30A0, 'end': 0x30FF }, // Katakana
{ 'begin': 0x3100, 'end': 0x312F }, // Bopomofo
{ 'begin': 0x3130, 'end': 0x318F }, // Hangul Compatibility Jamo
{ 'begin': 0xA840, 'end': 0xA87F }, // Phags-pa
{ 'begin': 0x3200, 'end': 0x32FF }, // Enclosed CJK Letters And Months
{ 'begin': 0x3300, 'end': 0x33FF }, // CJK Compatibility
{ 'begin': 0xAC00, 'end': 0xD7AF }, // Hangul Syllables
{ 'begin': 0xD800, 'end': 0xDFFF }, // Non-Plane 0 *
{ 'begin': 0x10900, 'end': 0x1091F }, // Phoenicia
{ 'begin': 0x4E00, 'end': 0x9FFF }, // CJK Unified Ideographs
{ 'begin': 0xE000, 'end': 0xF8FF }, // Private Use Area (plane 0)
{ 'begin': 0x31C0, 'end': 0x31EF }, // CJK Strokes
{ 'begin': 0xFB00, 'end': 0xFB4F }, // Alphabetic Presentation Forms
{ 'begin': 0xFB50, 'end': 0xFDFF }, // Arabic Presentation Forms-A
{ 'begin': 0xFE20, 'end': 0xFE2F }, // Combining Half Marks
{ 'begin': 0xFE10, 'end': 0xFE1F }, // Vertical Forms
{ 'begin': 0xFE50, 'end': 0xFE6F }, // Small Form Variants
{ 'begin': 0xFE70, 'end': 0xFEFF }, // Arabic Presentation Forms-B
{ 'begin': 0xFF00, 'end': 0xFFEF }, // Halfwidth And Fullwidth Forms
{ 'begin': 0xFFF0, 'end': 0xFFFF }, // Specials
{ 'begin': 0x0F00, 'end': 0x0FFF }, // Tibetan
{ 'begin': 0x0700, 'end': 0x074F }, // Syriac
{ 'begin': 0x0780, 'end': 0x07BF }, // Thaana
{ 'begin': 0x0D80, 'end': 0x0DFF }, // Sinhala
{ 'begin': 0x1000, 'end': 0x109F }, // Myanmar
{ 'begin': 0x1200, 'end': 0x137F }, // Ethiopic
{ 'begin': 0x13A0, 'end': 0x13FF }, // Cherokee
{ 'begin': 0x1400, 'end': 0x167F }, // Unified Canadian Aboriginal Syllabics
{ 'begin': 0x1680, 'end': 0x169F }, // Ogham
{ 'begin': 0x16A0, 'end': 0x16FF }, // Runic
{ 'begin': 0x1780, 'end': 0x17FF }, // Khmer
{ 'begin': 0x1800, 'end': 0x18AF }, // Mongolian
{ 'begin': 0x2800, 'end': 0x28FF }, // Braille Patterns
{ 'begin': 0xA000, 'end': 0xA48F }, // Yi Syllables
{ 'begin': 0x1700, 'end': 0x171F }, // Tagalog
{ 'begin': 0x10300, 'end': 0x1032F }, // Old Italic
{ 'begin': 0x10330, 'end': 0x1034F }, // Gothic
{ 'begin': 0x10400, 'end': 0x1044F }, // Deseret
{ 'begin': 0x1D000, 'end': 0x1D0FF }, // Byzantine Musical Symbols
{ 'begin': 0x1D400, 'end': 0x1D7FF }, // Mathematical Alphanumeric Symbols
{ 'begin': 0xFF000, 'end': 0xFFFFD }, // Private Use (plane 15)
{ 'begin': 0xFE00, 'end': 0xFE0F }, // Variation Selectors
{ 'begin': 0xE0000, 'end': 0xE007F }, // Tags
{ 'begin': 0x1900, 'end': 0x194F }, // Limbu
{ 'begin': 0x1950, 'end': 0x197F }, // Tai Le
{ 'begin': 0x1980, 'end': 0x19DF }, // New Tai Lue
{ 'begin': 0x1A00, 'end': 0x1A1F }, // Buginese
{ 'begin': 0x2C00, 'end': 0x2C5F }, // Glagolitic
{ 'begin': 0x2D30, 'end': 0x2D7F }, // Tifinagh
{ 'begin': 0x4DC0, 'end': 0x4DFF }, // Yijing Hexagram Symbols
{ 'begin': 0xA800, 'end': 0xA82F }, // Syloti Nagri
{ 'begin': 0x10000, 'end': 0x1007F }, // Linear B Syllabary
{ 'begin': 0x10140, 'end': 0x1018F }, // Ancient Greek Numbers
{ 'begin': 0x10380, 'end': 0x1039F }, // Ugaritic
{ 'begin': 0x103A0, 'end': 0x103DF }, // Old Persian
{ 'begin': 0x10450, 'end': 0x1047F }, // Shavian
{ 'begin': 0x10480, 'end': 0x104AF }, // Osmanya
{ 'begin': 0x10800, 'end': 0x1083F }, // Cypriot Syllabary
{ 'begin': 0x10A00, 'end': 0x10A5F }, // Kharoshthi
{ 'begin': 0x1D300, 'end': 0x1D35F }, // Tai Xuan Jing Symbols
{ 'begin': 0x12000, 'end': 0x123FF }, // Cuneiform
{ 'begin': 0x1D360, 'end': 0x1D37F }, // Counting Rod Numerals
{ 'begin': 0x1B80, 'end': 0x1BBF }, // Sundanese
{ 'begin': 0x1C00, 'end': 0x1C4F }, // Lepcha
{ 'begin': 0x1C50, 'end': 0x1C7F }, // Ol Chiki
{ 'begin': 0xA880, 'end': 0xA8DF }, // Saurashtra
{ 'begin': 0xA900, 'end': 0xA92F }, // Kayah Li
{ 'begin': 0xA930, 'end': 0xA95F }, // Rejang
{ 'begin': 0xAA00, 'end': 0xAA5F }, // Cham
{ 'begin': 0x10190, 'end': 0x101CF }, // Ancient Symbols
{ 'begin': 0x101D0, 'end': 0x101FF }, // Phaistos Disc
{ 'begin': 0x102A0, 'end': 0x102DF }, // Carian
{ 'begin': 0x1F030, 'end': 0x1F09F } // Domino Tiles
];
function getUnicodeRangeFor(value) {
for (var i = 0; i < UnicodeRanges.length; i++) {
var range = UnicodeRanges[i];
if (value >= range.begin && value < range.end)
return i;
}
return -1;
}
/**
* 'Font' is the class the outside world should use, it encapsulate all the font
* decoding logics whatever type it is (assuming the font type is supported).
*
* For example to read a Type1 font and to attach it to the document:
* var type1Font = new Font("MyFontName", binaryFile, propertiesObject);
* type1Font.bind();
*/
var Font = (function Font() {
var constructor = function font_constructor(name, file, properties) {
this.name = name;
this.encoding = properties.encoding;
this.sizes = [];
// If the font is to be ignored, register it like an already loaded font
// to avoid the cost of waiting for it be be loaded by the platform.
if (properties.ignore) {
this.loadedName = 'sans-serif';
this.loading = false;
return;
}
if (!file) {
// The file data is not specified. Trying to fix the font name
// to be used with the canvas.font.
var fontName = stdFontMap[name] || name.replace('_', '-');
this.bold = (fontName.indexOf('Bold') != -1);
this.italic = (fontName.indexOf('Oblique') != -1) ||
(fontName.indexOf('Italic') != -1);
this.loadedName = fontName.split('-')[0];
this.loading = false;
this.charsToUnicode = function(s) {
return s;
};
return;
}
var data;
switch (properties.type) {
case 'Type1':
case 'CIDFontType0':
this.mimetype = 'font/opentype';
var subtype = properties.subtype;
if (subtype === 'Type1C') {
var cff = new Type2CFF(file, properties);
} else {
var cff = new CFF(name, file, properties);
}
// Wrap the CFF data inside an OTF font file
data = this.convert(name, cff, properties);
break;
case 'TrueType':
case 'CIDFontType2':
this.mimetype = 'font/opentype';
// Repair the TrueType file if it is can be damaged in the point of
// view of the sanitizer
data = this.checkAndRepair(name, file, properties);
break;
default:
warn('Font ' + properties.type + ' is not supported');
break;
}
this.data = data;
this.type = properties.type;
this.textMatrix = properties.textMatrix;
this.loadedName = getUniqueName();
this.compositeFont = properties.compositeFont;
this.loading = true;
};
var numFonts = 0;
function getUniqueName() {
return 'pdfFont' + numFonts++;
}
function stringToArray(str) {
var array = [];
for (var i = 0; i < str.length; ++i)
array[i] = str.charCodeAt(i);
return array;
};
function int16(bytes) {
return (bytes[0] << 8) + (bytes[1] & 0xff);
};
function int32(bytes) {
return (bytes[0] << 24) + (bytes[1] << 16) +
(bytes[2] << 8) + (bytes[3] & 0xff);
};
function getMaxPower2(number) {
var maxPower = 0;
var value = number;
while (value >= 2) {
value /= 2;
maxPower++;
}
value = 2;
for (var i = 1; i < maxPower; i++)
value *= 2;
return value;
};
function string16(value) {
return String.fromCharCode((value >> 8) & 0xff) +
String.fromCharCode(value & 0xff);
};
function string32(value) {
return String.fromCharCode((value >> 24) & 0xff) +
String.fromCharCode((value >> 16) & 0xff) +
String.fromCharCode((value >> 8) & 0xff) +
String.fromCharCode(value & 0xff);
};
function createOpenTypeHeader(sfnt, file, offsets, numTables) {
// sfnt version (4 bytes)
var header = sfnt;
// numTables (2 bytes)
header += string16(numTables);
// searchRange (2 bytes)
var tablesMaxPower2 = getMaxPower2(numTables);
var searchRange = tablesMaxPower2 * 16;
header += string16(searchRange);
// entrySelector (2 bytes)
header += string16(Math.log(tablesMaxPower2) / Math.log(2));
// rangeShift (2 bytes)
header += string16(numTables * 16 - searchRange);
file.set(stringToArray(header), offsets.currentOffset);
offsets.currentOffset += header.length;
offsets.virtualOffset += header.length;
};
function createTableEntry(file, offsets, tag, data) {
// offset
var offset = offsets.virtualOffset;
// length
var length = data.length;
// Per spec tables must be 4-bytes align so add padding as needed
while (data.length & 3)
data.push(0x00);
while (offsets.virtualOffset & 3)
offsets.virtualOffset++;
// checksum
var checksum = 0, n = data.length;
for (var i = 0; i < n; i += 4)
checksum = (checksum + int32([data[i], data[i + 1], data[i + 2],
data[i + 3]])) | 0;
var tableEntry = (tag + string32(checksum) +
string32(offset) + string32(length));
tableEntry = stringToArray(tableEntry);
file.set(tableEntry, offsets.currentOffset);
offsets.currentOffset += tableEntry.length;
offsets.virtualOffset += data.length;
};
function getRanges(glyphs) {
// Array.sort() sorts by characters, not numerically, so convert to an
// array of characters.
var codes = [];
var length = glyphs.length;
for (var n = 0; n < length; ++n)
codes.push(String.fromCharCode(glyphs[n].unicode));
codes.sort();
// Split the sorted codes into ranges.
var ranges = [];
for (var n = 0; n < length; ) {
var start = codes[n++].charCodeAt(0);
var end = start;
while (n < length && end + 1 == codes[n].charCodeAt(0)) {
++end;
++n;
}
ranges.push([start, end]);
}
return ranges;
};
function createCMapTable(glyphs, deltas) {
var ranges = getRanges(glyphs);
var numTables = 1;
var cmap = '\x00\x00' + // version
string16(numTables) + // numTables
'\x00\x03' + // platformID
'\x00\x01' + // encodingID
string32(4 + numTables * 8); // start of the table record
var segCount = ranges.length + 1;
var segCount2 = segCount * 2;
var searchRange = getMaxPower2(segCount) * 2;
var searchEntry = Math.log(segCount) / Math.log(2);
var rangeShift = 2 * segCount - searchRange;
// Fill up the 4 parallel arrays describing the segments.
var startCount = '';
var endCount = '';
var idDeltas = '';
var idRangeOffsets = '';
var glyphsIds = '';
var bias = 0;
for (var i = 0; i < segCount - 1; i++) {
var range = ranges[i];
var start = range[0];
var end = range[1];
var offset = (segCount - i) * 2 + bias * 2;
bias += (end - start + 1);
startCount += string16(start);
endCount += string16(end);
idDeltas += string16(0);
idRangeOffsets += string16(offset);
}
for (var i = 0; i < glyphs.length; i++)
glyphsIds += string16(deltas ? deltas[i] : i + 1);
endCount += '\xFF\xFF';
startCount += '\xFF\xFF';
idDeltas += '\x00\x01';
idRangeOffsets += '\x00\x00';
var format314 = '\x00\x00' + // language
string16(segCount2) +
string16(searchRange) +
string16(searchEntry) +
string16(rangeShift) +
endCount + '\x00\x00' + startCount +
idDeltas + idRangeOffsets + glyphsIds;
return stringToArray(cmap +
'\x00\x04' + // format
string16(format314.length + 4) + // length
format314);
};
function createOS2Table(properties) {
var ulUnicodeRange1 = 0;
var ulUnicodeRange2 = 0;
var ulUnicodeRange3 = 0;
var ulUnicodeRange4 = 0;
var charset = properties.charset;
if (charset && charset.length) {
var firstCharIndex = null;
var lastCharIndex = 0;
for (var i = 0; i < charset.length; i++) {
var code = GlyphsUnicode[charset[i]];
if (firstCharIndex > code || !firstCharIndex)
firstCharIndex = code;
if (lastCharIndex < code)
lastCharIndex = code;
var position = getUnicodeRangeFor(code);
if (position < 32) {
ulUnicodeRange1 |= 1 << position;
} else if (position < 64) {
ulUnicodeRange2 |= 1 << position - 32;
} else if (position < 96) {
ulUnicodeRange3 |= 1 << position - 64;
} else if (position < 123) {
ulUnicodeRange4 |= 1 << position - 96;
} else {
error('Unicode ranges Bits > 123 are reserved for internal usage');
}
}
}
return '\x00\x03' + // version
'\x02\x24' + // xAvgCharWidth
'\x01\xF4' + // usWeightClass
'\x00\x05' + // usWidthClass
'\x00\x00' + // fstype (0 to let the font loads via font-face on IE)
'\x02\x8A' + // ySubscriptXSize
'\x02\xBB' + // ySubscriptYSize
'\x00\x00' + // ySubscriptXOffset
'\x00\x8C' + // ySubscriptYOffset
'\x02\x8A' + // ySuperScriptXSize
'\x02\xBB' + // ySuperScriptYSize
'\x00\x00' + // ySuperScriptXOffset
'\x01\xDF' + // ySuperScriptYOffset
'\x00\x31' + // yStrikeOutSize
'\x01\x02' + // yStrikeOutPosition
'\x00\x00' + // sFamilyClass
'\x00\x00\x06' +
String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) +
'\x00\x00\x00\x00\x00\x00' + // Panose
string32(ulUnicodeRange1) + // ulUnicodeRange1 (Bits 0-31)
string32(ulUnicodeRange2) + // ulUnicodeRange2 (Bits 32-63)
string32(ulUnicodeRange3) + // ulUnicodeRange3 (Bits 64-95)
string32(ulUnicodeRange4) + // ulUnicodeRange4 (Bits 96-127)
'\x2A\x32\x31\x2A' + // achVendID
string16(properties.italicAngle ? 1 : 0) + // fsSelection
string16(firstCharIndex ||
properties.firstChar) + // usFirstCharIndex
string16(lastCharIndex || properties.lastChar) + // usLastCharIndex
string16(properties.ascent) + // sTypoAscender
string16(properties.descent) + // sTypoDescender
'\x00\x64' + // sTypoLineGap (7%-10% of the unitsPerEM value)
string16(properties.ascent) + // usWinAscent
string16(-properties.descent) + // usWinDescent
'\x00\x00\x00\x00' + // ulCodePageRange1 (Bits 0-31)
'\x00\x00\x00\x00' + // ulCodePageRange2 (Bits 32-63)
string16(properties.xHeight) + // sxHeight
string16(properties.capHeight) + // sCapHeight
string16(0) + // usDefaultChar
string16(firstCharIndex || properties.firstChar) + // usBreakChar
'\x00\x03'; // usMaxContext
};
function createPostTable(properties) {
var angle = Math.floor(properties.italicAngle * (Math.pow(2, 16)));
return '\x00\x03\x00\x00' + // Version number
string32(angle) + // italicAngle
'\x00\x00' + // underlinePosition
'\x00\x00' + // underlineThickness
string32(properties.fixedPitch) + // isFixedPitch
'\x00\x00\x00\x00' + // minMemType42
'\x00\x00\x00\x00' + // maxMemType42
'\x00\x00\x00\x00' + // minMemType1
'\x00\x00\x00\x00'; // maxMemType1
};
function createNameTable(name) {
var strings = [
'Original licence', // 0.Copyright
name, // 1.Font family
'Unknown', // 2.Font subfamily (font weight)
'uniqueID', // 3.Unique ID
name, // 4.Full font name
'Version 0.11', // 5.Version
'', // 6.Postscript name
'Unknown', // 7.Trademark
'Unknown', // 8.Manufacturer
'Unknown' // 9.Designer
];
// Mac want 1-byte per character strings while Windows want
// 2-bytes per character, so duplicate the names table
var stringsUnicode = [];
for (var i = 0; i < strings.length; i++) {
var str = strings[i];
var strUnicode = '';
for (var j = 0; j < str.length; j++)
strUnicode += string16(str.charCodeAt(j));
stringsUnicode.push(strUnicode);
}
var names = [strings, stringsUnicode];
var platforms = ['\x00\x01', '\x00\x03'];
var encodings = ['\x00\x00', '\x00\x01'];
var languages = ['\x00\x00', '\x04\x09'];
var namesRecordCount = strings.length * platforms.length;
var nameTable =
'\x00\x00' + // format
string16(namesRecordCount) + // Number of names Record
string16(namesRecordCount * 12 + 6); // Storage
// Build the name records field
var strOffset = 0;
for (var i = 0; i < platforms.length; i++) {
var strs = names[i];
for (var j = 0; j < strs.length; j++) {
var str = strs[j];
var nameRecord =
platforms[i] + // platform ID
encodings[i] + // encoding ID
languages[i] + // language ID
string16(j) + // name ID
string16(str.length) +
string16(strOffset);
nameTable += nameRecord;
strOffset += str.length;
}
}
nameTable += strings.join('') + stringsUnicode.join('');
return nameTable;
}
constructor.prototype = {
name: null,
font: null,
mimetype: null,
encoding: null,
checkAndRepair: function font_checkAndRepair(name, font, properties) {
var kCmapGlyphOffset = 0xFF;
function readTableEntry(file) {
// tag
var tag = file.getBytes(4);
tag = String.fromCharCode(tag[0]) +
String.fromCharCode(tag[1]) +
String.fromCharCode(tag[2]) +
String.fromCharCode(tag[3]);
var checksum = int32(file.getBytes(4));
var offset = int32(file.getBytes(4));
var length = int32(file.getBytes(4));
// Read the table associated data
var previousPosition = file.pos;
file.pos = file.start ? file.start : 0;
file.skip(offset);
var data = file.getBytes(length);
file.pos = previousPosition;
if (tag == 'head')
// clearing checksum adjustment
data[8] = data[9] = data[10] = data[11] = 0;
return {
tag: tag,
checksum: checksum,
length: length,
offset: offset,
data: data
};
};
function readOpenTypeHeader(ttf) {
return {
version: ttf.getBytes(4),
numTables: int16(ttf.getBytes(2)),
searchRange: int16(ttf.getBytes(2)),
entrySelector: int16(ttf.getBytes(2)),
rangeShift: int16(ttf.getBytes(2))
};
};
function replaceCMapTable(cmap, font, properties) {
var start = (font.start ? font.start : 0) + cmap.offset;
font.pos = start;
var version = int16(font.getBytes(2));
var numRecords = int16(font.getBytes(2));
var records = [];
for (var i = 0; i < numRecords; i++) {
records.push({
platformID: int16(font.getBytes(2)),
encodingID: int16(font.getBytes(2)),
offset: int32(font.getBytes(4))
});
}
var encoding = properties.encoding;
var charset = properties.charset;
for (var i = 0; i < numRecords; i++) {
var table = records[i];
font.pos = start + table.offset;
var format = int16(font.getBytes(2));
var length = int16(font.getBytes(2));
var language = int16(font.getBytes(2));
if (format == 0) {
// Characters below 0x20 are controls characters that are hardcoded
// into the platform so if some characters in the font are assigned
// under this limit they will not be displayed so let's rewrite the
// CMap.
var glyphs = [];
var deltas = [];
for (var j = 0; j < 256; j++) {
var index = font.getByte();
if (index) {
deltas.push(index);
glyphs.push({ unicode: j });
}
}
var rewrite = false;
for (var code in encoding) {
if (code < 0x20 && encoding[code])
rewrite = true;
if (rewrite)
encoding[code] = parseInt(code) + 0x1F;
}
if (rewrite) {
for (var j = 0; j < glyphs.length; j++) {
glyphs[j].unicode += 0x1F;
}
}
cmap.data = createCMapTable(glyphs, deltas);
} else if (format == 6 && numRecords == 1 && !encoding.empty) {
// Format 0 alone is not allowed by the sanitizer so let's rewrite
// that to a 3-1-4 Unicode BMP table
TODO('Use an other source of informations than ' +
'charset here, it is not reliable');
var glyphs = [];
for (var j = 0; j < charset.length; j++) {
glyphs.push({
unicode: GlyphsUnicode[charset[j]] || 0
});
}
cmap.data = createCMapTable(glyphs);
} else if (format == 6 && numRecords == 1) {
// Format 6 is a 2-bytes dense mapping, which means the font data
// lives glue together even if they are pretty far in the unicode
// table. (This looks weird, so I can have missed something), this
// works on Linux but seems to fails on Mac so let's rewrite the
// cmap table to a 3-1-4 style
var firstCode = int16(font.getBytes(2));
var entryCount = int16(font.getBytes(2));
var glyphs = [];
var min = 0xffff, max = 0;
for (var j = 0; j < entryCount; j++) {
var charcode = int16(font.getBytes(2));
glyphs.push(charcode);
if (charcode < min)
min = charcode;
if (charcode > max)
max = charcode;
}
// Since Format 6 is a dense array, check for gaps
for (var j = min; j < max; j++) {
if (glyphs.indexOf(j) == -1)
glyphs.push(j);
}
for (var j = 0; j < glyphs.length; j++)
glyphs[j] = { unicode: glyphs[j] + firstCode };
var ranges = getRanges(glyphs);
assert(ranges.length == 1, 'Got ' + ranges.length +
' ranges in a dense array');
var denseRange = ranges[0];
var start = denseRange[0];
var end = denseRange[1];
var index = firstCode;
for (var j = start; j <= end; j++)
encoding[index++] = glyphs[j - firstCode - 1].unicode;
cmap.data = createCMapTable(glyphs);
}
}
};
// Check that required tables are present
var requiredTables = ['OS/2', 'cmap', 'head', 'hhea',
'hmtx', 'maxp', 'name', 'post'];
var header = readOpenTypeHeader(font);
var numTables = header.numTables;
var cmap, maxp, hhea, hmtx;
var tables = [];
for (var i = 0; i < numTables; i++) {
var table = readTableEntry(font);
var index = requiredTables.indexOf(table.tag);
if (index != -1) {
if (table.tag == 'cmap')
cmap = table;
else if (table.tag == 'maxp')
maxp = table;
else if (table.tag == 'hhea')
hhea = table;
else if (table.tag == 'hmtx')
hmtx = table;
requiredTables.splice(index, 1);
}
tables.push(table);
}
// Create a new file to hold the new version of our truetype with a new
// header and new offsets
var ttf = new Uint8Array(kMaxFontFileSize);
// The offsets object holds at the same time a representation of where
// to write the table entry information about a table and another offset
// representing the offset where to put the actual data of a particular
// table
var numTables = header.numTables + requiredTables.length;
var offsets = {
currentOffset: 0,
virtualOffset: numTables * (4 * 4)
};
// The new numbers of tables will be the last one plus the num
// of missing tables
createOpenTypeHeader('\x00\x01\x00\x00', ttf, offsets, numTables);
if (requiredTables.indexOf('OS/2') != -1) {
tables.push({
tag: 'OS/2',
data: stringToArray(createOS2Table(properties))
});
}
// Ensure the hmtx tables contains an advance width and a sidebearing
// for the number of glyphs declared in the maxp table
font.pos = (font.start ? font.start : 0) + maxp.offset;
var version = int16(font.getBytes(4));
var numGlyphs = int16(font.getBytes(2));
font.pos = (font.start ? font.start : 0) + hhea.offset;
font.pos += hhea.length - 2;
var numOfHMetrics = int16(font.getBytes(2));
var numOfSidebearings = numGlyphs - numOfHMetrics;
var numMissing = numOfSidebearings -
((hmtx.length - numOfHMetrics * 4) >> 1);
if (numMissing > 0) {
font.pos = (font.start ? font.start : 0) + hmtx.offset;
var metrics = '';
for (var i = 0; i < hmtx.length; i++)
metrics += String.fromCharCode(font.getByte());
for (var i = 0; i < numMissing; i++)
metrics += '\x00\x00';
hmtx.data = stringToArray(metrics);
}
// Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth
// Sometimes it's 0. That needs to be fixed
if (hhea.data[10] == 0 && hhea.data[11] == 0) {
hhea.data[10] = 0xFF;
hhea.data[11] = 0xFF;
}
// Replace the old CMAP table with a shiny new one
if (properties.type == 'CIDFontType2') {
// Type2 composite fonts map characters directly to glyphs so the cmap
// table must be replaced.
// canvas fillText will reencode some characters even if the font has a
// glyph at that position - e.g. newline is converted to a space and U+00AD
// (soft hypen) is not drawn.
// So, offset all the glyphs by 0xFF to avoid these cases and use
// the encoding to map incoming characters to the new glyph positions
var glyphs = [];
var encoding = properties.encoding;
for (var i = 1; i < numGlyphs; i++) {
glyphs.push({ unicode: i + kCmapGlyphOffset });
}
if ('undefined' == typeof(encoding[0])) {
// the font is directly characters to glyphs with no encoding
// so create an identity encoding
for (i = 0; i < numGlyphs; i++)
encoding[i] = i + kCmapGlyphOffset;
} else {
for (var i in encoding)
encoding[i] = encoding[i] + kCmapGlyphOffset;
}
if (!cmap) {
cmap = {
tag: 'cmap',
data: null
};
tables.push(cmap);
}
cmap.data = createCMapTable(glyphs);
} else {
replaceCMapTable(cmap, font, properties);
}
// Rewrite the 'post' table if needed
if (requiredTables.indexOf('post') != -1) {
tables.push({
tag: 'post',
data: stringToArray(createPostTable(properties))
});
}
// Rewrite the 'name' table if needed
if (requiredTables.indexOf('name') != -1) {
tables.push({
tag: 'name',
data: stringToArray(createNameTable(this.name))
});
}
// Tables needs to be written by ascendant alphabetic order
tables.sort(function tables_sort(a, b) {
return (a.tag > b.tag) - (a.tag < b.tag);
});
// rewrite the tables but tweak offsets
for (var i = 0; i < tables.length; i++) {
var table = tables[i];
var data = [];
var tableData = table.data;
for (var j = 0; j < tableData.length; j++)
data.push(tableData[j]);
createTableEntry(ttf, offsets, table.tag, data);
}
// Add the table datas
for (var i = 0; i < tables.length; i++) {
var table = tables[i];
var tableData = table.data;
ttf.set(tableData, offsets.currentOffset);
offsets.currentOffset += tableData.length;
// 4-byte aligned data
while (offsets.currentOffset & 3)
offsets.currentOffset++;
}
var fontData = [];
for (var i = 0; i < offsets.currentOffset; i++)
fontData.push(ttf[i]);
return fontData;
},
convert: function font_convert(fontName, font, properties) {
function isFixedPitch(glyphs) {
for (var i = 0; i < glyphs.length - 1; i++) {
if (glyphs[i] != glyphs[i + 1])
return false;
}
return true;
};
// The offsets object holds at the same time a representation of where
// to write the table entry information about a table and another offset
// representing the offset where to draw the actual data of a particular
// table
var kRequiredTablesCount = 9;
var offsets = {
currentOffset: 0,
virtualOffset: 9 * (4 * 4)
};
var otf = new Uint8Array(kMaxFontFileSize);
createOpenTypeHeader('\x4F\x54\x54\x4F', otf, offsets, 9);
var charstrings = font.charstrings;
properties.fixedPitch = isFixedPitch(charstrings);
var fields = {
// PostScript Font Program
'CFF ': font.data,
// OS/2 and Windows Specific metrics
'OS/2': stringToArray(createOS2Table(properties)),
// Character to glyphs mapping
'cmap': createCMapTable(charstrings.slice(), font.glyphIds),
// Font header
'head': (function() {
return stringToArray(
'\x00\x01\x00\x00' + // Version number
'\x00\x00\x10\x00' + // fontRevision
'\x00\x00\x00\x00' + // checksumAdjustement
'\x5F\x0F\x3C\xF5' + // magicNumber
'\x00\x00' + // Flags
'\x03\xE8' + // unitsPerEM (defaulting to 1000)
'\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date
'\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date
'\x00\x00' + // xMin
string16(properties.descent) + // yMin
'\x0F\xFF' + // xMax
string16(properties.ascent) + // yMax
string16(properties.italicAngle ? 2 : 0) + // macStyle
'\x00\x11' + // lowestRecPPEM
'\x00\x00' + // fontDirectionHint
'\x00\x00' + // indexToLocFormat
'\x00\x00'); // glyphDataFormat
})(),
// Horizontal header
'hhea': (function() {
return stringToArray(
'\x00\x01\x00\x00' + // Version number
string16(properties.ascent) + // Typographic Ascent
string16(properties.descent) + // Typographic Descent
'\x00\x00' + // Line Gap
'\xFF\xFF' + // advanceWidthMax
'\x00\x00' + // minLeftSidebearing
'\x00\x00' + // minRightSidebearing
'\x00\x00' + // xMaxExtent
string16(properties.capHeight) + // caretSlopeRise
string16(Math.tan(properties.italicAngle) *
properties.xHeight) + // caretSlopeRun
'\x00\x00' + // caretOffset
'\x00\x00' + // -reserved-
'\x00\x00' + // -reserved-
'\x00\x00' + // -reserved-
'\x00\x00' + // -reserved-
'\x00\x00' + // metricDataFormat
string16(charstrings.length + 1)); // Number of HMetrics
})(),
// Horizontal metrics
'hmtx': (function() {
var hmtx = '\x00\x00\x00\x00'; // Fake .notdef
for (var i = 0; i < charstrings.length; i++) {
hmtx += string16(charstrings[i].width) + string16(0);
}
return stringToArray(hmtx);
})(),
// Maximum profile
'maxp': (function() {
return stringToArray(
'\x00\x00\x50\x00' + // Version number
string16(charstrings.length + 1)); // Num of glyphs
})(),
// Naming tables
'name': stringToArray(createNameTable(fontName)),
// PostScript informations
'post': stringToArray(createPostTable(properties))
};
for (var field in fields)
createTableEntry(otf, offsets, field, fields[field]);
for (var field in fields) {
var table = fields[field];
otf.set(table, offsets.currentOffset);
offsets.currentOffset += table.length;
}
var fontData = [];
for (var i = 0; i < offsets.currentOffset; i++)
fontData.push(otf[i]);
return fontData;
},
bindWorker: function font_bindWorker(data) {
postMessage({
action: 'font',
data: {
raw: data,
fontName: this.loadedName,
mimetype: this.mimetype
}
});
},
bindDOM: function font_bindDom(data) {
var fontName = this.loadedName;
// Add the font-face rule to the document
var url = ('url(data:' + this.mimetype + ';base64,' +
window.btoa(data) + ');');
var rule = "@font-face { font-family:'" + fontName + "';src:" + url + '}';
var styleSheet = document.styleSheets[0];
styleSheet.insertRule(rule, styleSheet.cssRules.length);
return rule;
},
charsToUnicode: function fonts_chars2Unicode(chars) {
var charsCache = this.charsCache;
var str;
// if we translated this string before, just grab it from the cache
if (charsCache) {
str = charsCache[chars];
if (str)
return str;
}
// lazily create the translation cache
if (!charsCache)
charsCache = this.charsCache = Object.create(null);
// translate the string using the font's encoding
var encoding = this.encoding;
if (!encoding)
return chars;
str = '';
if (this.compositeFont) {
// composite fonts have multi-byte strings convert the string from
// single-byte to multi-byte
// XXX assuming CIDFonts are two-byte - later need to extract the
// correct byte encoding according to the PDF spec
var length = chars.length - 1; // looping over two bytes at a time so
// loop should never end on the last byte
for (var i = 0; i < length; i++) {
var charcode = int16([chars.charCodeAt(i++), chars.charCodeAt(i)]);
var unicode = encoding[charcode];
str += String.fromCharCode(unicode);
}
}
else {
for (var i = 0; i < chars.length; ++i) {
var charcode = chars.charCodeAt(i);
var unicode = encoding[charcode];
if ('undefined' == typeof(unicode)) {
// FIXME/issue 233: we're hitting this in test/pdf/sizes.pdf
// at the moment, for unknown reasons.
warn('Unencoded charcode ' + charcode);
unicode = charcode;
}
// Check if the glyph has already been converted
if (!IsNum(unicode))
unicode = encoding[unicode] = GlyphsUnicode[unicode.name];
// Handle surrogate pairs
if (unicode > 0xFFFF) {
str += String.fromCharCode(unicode & 0xFFFF);
unicode >>= 16;
}
str += String.fromCharCode(unicode);
}
}
// Enter the translated string into the cache
return charsCache[chars] = str;
}
};
return constructor;
})();
/**
* Type1Parser encapsulate the needed code for parsing a Type1 font
* program. Some of its logic depends on the Type2 charstrings
* structure.
*/
var Type1Parser = function() {
/*
* Decrypt a Sequence of Ciphertext Bytes to Produce the Original Sequence
* of Plaintext Bytes. The function took a key as a parameter which can be
* for decrypting the eexec block of for decoding charStrings.
*/
var kEexecEncryptionKey = 55665;
var kCharStringsEncryptionKey = 4330;
function decrypt(stream, key, discardNumber) {
var r = key, c1 = 52845, c2 = 22719;
var decryptedString = [];
var value = '';
var count = stream.length;
for (var i = 0; i < count; i++) {
value = stream[i];
decryptedString[i] = value ^ (r >> 8);
r = ((value + r) * c1 + c2) & ((1 << 16) - 1);
}
return decryptedString.slice(discardNumber);
};
/*
* CharStrings are encoded following the the CharString Encoding sequence
* describe in Chapter 6 of the "Adobe Type1 Font Format" specification.
* The value in a byte indicates a command, a number, or subsequent bytes
* that are to be interpreted in a special way.
*
* CharString Number Encoding:
* A CharString byte containing the values from 32 through 255 inclusive
* indicate an integer. These values are decoded in four ranges.
*
* 1. A CharString byte containing a value, v, between 32 and 246 inclusive,
* indicate the integer v - 139. Thus, the integer values from -107 through
* 107 inclusive may be encoded in single byte.
*
* 2. A CharString byte containing a value, v, between 247 and 250 inclusive,
* indicates an integer involving the next byte, w, according to the formula:
* [(v - 247) x 256] + w + 108
*
* 3. A CharString byte containing a value, v, between 251 and 254 inclusive,
* indicates an integer involving the next byte, w, according to the formula:
* -[(v - 251) * 256] - w - 108
*
* 4. A CharString containing the value 255 indicates that the next 4 bytes
* are a two complement signed integer. The first of these bytes contains the
* highest order bits, the second byte contains the next higher order bits
* and the fourth byte contain the lowest order bits.
*
*
* CharString Command Encoding:
* CharStrings commands are encoded in 1 or 2 bytes.
*
* Single byte commands are encoded in 1 byte that contains a value between
* 0 and 31 inclusive.
* If a command byte contains the value 12, then the value in the next byte
* indicates a command. This "escape" mechanism allows many extra commands
* to be encoded and this encoding technique helps to minimize the length of
* the charStrings.
*/
var charStringDictionary = {
'1': 'hstem',
'3': 'vstem',
'4': 'vmoveto',
'5': 'rlineto',
'6': 'hlineto',
'7': 'vlineto',
'8': 'rrcurveto',
// closepath is a Type1 command that do not take argument and is useless
// in Type2 and it can simply be ignored.
'9': null, // closepath
'10': 'callsubr',
// return is normally used inside sub-routines to tells to the execution
// flow that it can be back to normal.
// During the translation process Type1 charstrings will be flattened and
// sub-routines will be embedded directly into the charstring directly, so
// this can be ignored safely.
'11': 'return',
'12': {
// dotsection is a Type1 command to specify some hinting feature for dots
// that do not take a parameter and it can safely be ignored for Type2.
'0': null, // dotsection
// [vh]stem3 are Type1 only and Type2 supports [vh]stem with multiple
// parameters, so instead of returning [vh]stem3 take a shortcut and
// return [vhstem] instead.
'1': 'vstem',
'2': 'hstem',
// Type1 only command with command not (yet) built-in ,throw an error
'6': -1, // seac
'7': -1, //sbw
'11': 'sub',
'12': 'div',
// callothersubr is a mechanism to make calls on the postscript
// interpreter, this is not supported by Type2 charstring but hopefully
// most of the default commands can be ignored safely.
'16': 'callothersubr',
'17': 'pop',
// setcurrentpoint sets the current point to x, y without performing a
// moveto (this is a one shot positionning command). This is used only
// with the return of an OtherSubrs call.
// TODO Implement the OtherSubrs charstring embedding and replace this
// call by a no-op, like 2 'pop' commands for example.
'33': null //setcurrentpoint
},
'13': 'hsbw',
'14': 'endchar',
'21': 'rmoveto',
'22': 'hmoveto',
'30': 'vhcurveto',
'31': 'hvcurveto'
};
var kEscapeCommand = 12;
function decodeCharString(array) {
var charstring = [];
var lsb = 0;
var width = 0;
var used = false;
var value = '';
var count = array.length;
for (var i = 0; i < count; i++) {
value = array[i];
if (value < 32) {
var command = null;
if (value == kEscapeCommand) {
var escape = array[++i];
// TODO Clean this code
if (escape == 16) {
var index = charstring.pop();
var argc = charstring.pop();
for (var j = 0; j < argc; j++)
charstring.push('drop');
// If the flex mechanishm is not used in a font program, Adobe
// state that that entries 0, 1 and 2 can simply be replace by
// {}, which means that we can simply ignore them.
if (index < 3) {
continue;
}
// This is the same things about hint replacement, if it is not used
// entry 3 can be replaced by {3}
if (index == 3) {
charstring.push(3);
i++;
continue;
}
}
command = charStringDictionary['12'][escape];
} else {
// TODO Clean this code
if (value == 13) {
if (charstring.length == 2) {
width = charstring[1];
} else if (charstring.length == 4 && charstring[3] == 'div') {
width = charstring[1] / charstring[2];
} else {
error('Unsupported hsbw format: ' + charstring);
}
lsb = charstring[0];
charstring.push(lsb, 'hmoveto');
charstring.splice(0, 1);
continue;
}
command = charStringDictionary[value];
}
// Some charstring commands are meaningless in Type2 and will return
// a null, let's just ignored them
if (!command && i < count) {
continue;
} else if (!command) {
break;
} else if (command == -1) {
error('Support for Type1 command ' + value +
' (' + escape + ') is not implemented in charstring: ' +
charString);
}
value = command;
} else if (value <= 246) {
value = value - 139;
} else if (value <= 250) {
value = ((value - 247) * 256) + array[++i] + 108;
} else if (value <= 254) {
value = -((value - 251) * 256) - array[++i] - 108;
} else {
value = (array[++i] & 0xff) << 24 | (array[++i] & 0xff) << 16 |
(array[++i] & 0xff) << 8 | (array[++i] & 0xff) << 0;
}
charstring.push(value);
}
return { charstring: charstring, width: width, lsb: lsb };
};
/**
* Returns an object containing a Subrs array and a CharStrings
* array extracted from and eexec encrypted block of data
*/
function readNumberArray(str, index) {
var start = ++index;
var count = 0;
while (str[index++] != ']')
count++;
var array = str.substr(start, count).split(' ');
for (var i = 0; i < array.length; i++)
array[i] = parseFloat(array[i] || 0);
return array;
};
function readNumber(str, index) {
while (str[index++] == ' ');
var start = index;
var count = 0;
while (str[index++] != ' ')
count++;
return parseFloat(str.substr(start, count) || 0);
};
this.extractFontProgram = function t1_extractFontProgram(stream) {
var eexec = decrypt(stream, kEexecEncryptionKey, 4);
var eexecStr = '';
for (var i = 0; i < eexec.length; i++)
eexecStr += String.fromCharCode(eexec[i]);
var glyphsSection = false, subrsSection = false;
var program = {
subrs: [],
charstrings: [],
properties: {
'private': {}
}
};
var glyph = '';
var token = '';
var length = 0;
var c = '';
var count = eexecStr.length;
for (var i = 0; i < count; i++) {
var getToken = function() {
while(i < count && (eexecStr[i] == ' ' || eexecStr[i] == '\n'))
++i;
var t = '';
while(i < count && !(eexecStr[i] == ' ' || eexecStr[i] == '\n'))
t += eexecStr[i++];
return t;
}
var c = eexecStr[i];
if ((glyphsSection || subrsSection) && c == 'R') {
var data = eexec.slice(i + 3, i + 3 + length);
var encoded = decrypt(data, kCharStringsEncryptionKey, 4);
var str = decodeCharString(encoded);
if (glyphsSection) {
program.charstrings.push({
glyph: glyph,
data: str.charstring,
lsb: str.lsb,
width: str.width
});
} else {
program.subrs.push(str.charstring);
}
i += length + 3;
} else if (c == ' ' || c == '\n') {
length = parseInt(token);
token = '';
} else {
token += c;
if (!glyphsSection) {
switch (token) {
case '/CharString':
glyphsSection = true;
break;
case '/Subrs':
++i;
var num = parseInt(getToken());
getToken(); // read in 'array'
for (var j = 0; j < num; ++j) {
var t = getToken(); // read in 'dup'
if (t == 'ND')
break;
var index = parseInt(getToken());
if (index > j)
j = index;
var length = parseInt(getToken());
getToken(); // read in 'RD'
var data = eexec.slice(i + 1, i + 1 + length);
var encoded = decrypt(data, kCharStringsEncryptionKey, 4);
var str = decodeCharString(encoded);
i = i + 1 + length;
getToken(); //read in 'NP'
program.subrs[index] = str.charstring;
}
break;
case '/BlueValues':
case '/OtherBlues':
case '/FamilyBlues':
case '/FamilyOtherBlues':
case '/StemSnapH':
case '/StemSnapV':
program.properties.private[token.substring(1)] =
readNumberArray(eexecStr, i + 2);
break;
case '/StdHW':
case '/StdVW':
program.properties.private[token.substring(1)] =
readNumberArray(eexecStr, i + 2)[0];
break;
case '/BlueShift':
case '/BlueFuzz':
case '/BlueScale':
case '/LanguageGroup':
case '/ExpansionFactor':
program.properties.private[token.substring(1)] =
readNumber(eexecStr, i + 1);
break;
}
} else if (c == '/') {
token = glyph = '';
while ((c = eexecStr[++i]) != ' ')
glyph += c;
}
}
}
return program;
},
this.extractFontHeader = function t1_extractFontProgram(stream) {
var headerString = '';
for (var i = 0; i < stream.length; i++)
headerString += String.fromCharCode(stream[i]);
var info = {
textMatrix: null
};
var token = '';
var count = headerString.length;
for (var i = 0; i < count; i++) {
var c = headerString[i];
if (c == ' ' || c == '\n') {
switch (token) {
case '/FontMatrix':
var matrix = readNumberArray(headerString, i + 1);
// The FontMatrix is in unitPerEm, so make it pixels
for (var j = 0; j < matrix.length; j++)
matrix[j] *= 1000;
// Make the angle into the right direction
matrix[2] *= -1;
info.textMatrix = matrix;
break;
}
token = '';
} else {
token += c;
}
}
return info;
};
};
/**
* The CFF class takes a Type1 file and wrap it into a 'Compact Font Format',
* which itself embed Type2 charstrings.
*/
var CFFStrings = [
'.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
'equal', 'greater', 'question', 'at', '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', 'bracketleft', 'backslash', 'bracketright', 'asciicircum',
'underscore', 'quoteleft', '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', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase',
'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown',
'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent',
'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash',
'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae',
'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior',
'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn',
'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters',
'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior',
'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring',
'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave',
'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute',
'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute',
'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron',
'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde',
'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute',
'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex',
'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex',
'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall',
'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall',
'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', '266 ff',
'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle',
'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior',
'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior',
'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior',
'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior',
'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall',
'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior',
'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth',
'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds',
'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior',
'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior',
'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior',
'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior',
'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall',
'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall',
'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall',
'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall',
'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall',
'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003',
'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'
];
var type1Parser = new Type1Parser();
var CFF = function(name, file, properties) {
// Get the data block containing glyphs and subrs informations
var length1 = file.dict.get('Length1');
var length2 = file.dict.get('Length2');
var headerBlock = file.getBytes(length1);
var header = type1Parser.extractFontHeader(headerBlock);
for (var info in header)
properties[info] = header[info];
// Decrypt the data blocks and retrieve it's content
var eexecBlock = file.getBytes(length2);
var data = type1Parser.extractFontProgram(eexecBlock);
for (var info in data.properties)
properties[info] = data.properties[info];
var charstrings = this.getOrderedCharStrings(data.charstrings);
var type2Charstrings = this.getType2Charstrings(charstrings);
var subrs = this.getType2Subrs(data.subrs);
this.charstrings = charstrings;
this.data = this.wrap(name, type2Charstrings, this.charstrings,
subrs, properties);
};
CFF.prototype = {
createCFFIndexHeader: function cff_createCFFIndexHeader(objects, isByte) {
// First 2 bytes contains the number of objects contained into this index
var count = objects.length;
// If there is no object, just create an array saying that with another
// offset byte.
if (count == 0)
return '\x00\x00\x00';
var data = String.fromCharCode(count >> 8, count & 0xff);
// Next byte contains the offset size use to reference object in the file
// Actually we're using 0x04 to be sure to be able to store everything
// without thinking of it while coding.
data += '\x04';
// Add another offset after this one because we need a new offset
var relativeOffset = 1;
for (var i = 0; i < count + 1; i++) {
data += String.fromCharCode((relativeOffset >>> 24) & 0xFF,
(relativeOffset >> 16) & 0xFF,
(relativeOffset >> 8) & 0xFF,
relativeOffset & 0xFF);
if (objects[i])
relativeOffset += objects[i].length;
}
for (var i = 0; i < count; i++) {
for (var j = 0; j < objects[i].length; j++)
data += isByte ? String.fromCharCode(objects[i][j] & 0xFF) :
objects[i][j];
}
return data;
},
encodeNumber: function cff_encodeNumber(value) {
if (value >= -32768 && value <= 32767) {
return '\x1c' +
String.fromCharCode((value >> 8) & 0xFF) +
String.fromCharCode(value & 0xFF);
} else if (value >= (-2147483648) && value <= 2147483647) {
value ^= 0xffffffff;
value += 1;
return '\xff' +
String.fromCharCode((value >> 24) & 0xFF) +
String.fromCharCode((value >> 16) & 0xFF) +
String.fromCharCode((value >> 8) & 0xFF) +
String.fromCharCode(value & 0xFF);
}
error('Value: ' + value + ' is not allowed');
return null;
},
getOrderedCharStrings: function cff_getOrderedCharStrings(glyphs) {
var charstrings = [];
for (var i = 0; i < glyphs.length; i++) {
var glyph = glyphs[i];
var unicode = GlyphsUnicode[glyph.glyph];
if (!unicode) {
if (glyph.glyph != '.notdef') {
warn(glyph.glyph +
' does not have an entry in the glyphs unicode dictionary');
}
} else {
charstrings.push({
glyph: glyph,
unicode: unicode,
charstring: glyph.data,
width: glyph.width,
lsb: glyph.lsb
});
}
}
charstrings.sort(function charstrings_sort(a, b) {
return a.unicode - b.unicode;
});
return charstrings;
},
getType2Charstrings: function cff_getType2Charstrings(type1Charstrings) {
var type2Charstrings = [];
var count = type1Charstrings.length;
for (var i = 0; i < count; i++) {
var charstring = type1Charstrings[i].charstring;
type2Charstrings.push(this.flattenCharstring(charstring.slice(),
this.commandsMap));
}
return type2Charstrings;
},
getType2Subrs: function cff_getType2Charstrings(type1Subrs) {
var bias = 0;
var count = type1Subrs.length;
if (count < 1240)
bias = 107;
else if (count < 33900)
bias = 1131;
else
bias = 32768;
// Add a bunch of empty subrs to deal with the Type2 bias
var type2Subrs = [];
for (var i = 0; i < bias; i++)
type2Subrs.push([0x0B]);
for (var i = 0; i < count; i++) {
var subr = type1Subrs[i];
if (!subr)
subr = [0x0B];
type2Subrs.push(this.flattenCharstring(subr, this.commandsMap));
}
return type2Subrs;
},
/*
* Flatten the commands by interpreting the postscript code and replacing
* every 'callsubr', 'callothersubr' by the real commands.
*/
commandsMap: {
'hstem': 1,
'vstem': 3,
'vmoveto': 4,
'rlineto': 5,
'hlineto': 6,
'vlineto': 7,
'rrcurveto': 8,
'callsubr': 10,
'return': 11,
'sub': [12, 11],
'div': [12, 12],
'pop': [1, 12, 18],
'drop' : [12, 18],
'endchar': 14,
'rmoveto': 21,
'hmoveto': 22,
'vhcurveto': 30,
'hvcurveto': 31
},
flattenCharstring: function flattenCharstring(charstring, map) {
for (var i = 0; i < charstring.length; i++) {
var command = charstring[i];
if (command.charAt) {
var cmd = map[command];
assert(cmd, 'Unknow command: ' + command);
if (IsArray(cmd)) {
charstring.splice(i++, 1, cmd[0], cmd[1]);
} else {
charstring[i] = cmd;
}
} else {
// Type1 charstring use a division for number above 32000
if (command > 32000) {
var divisor = charstring[i + 1];
command /= divisor;
charstring.splice(i, 3, 28, command >> 8, command & 0xff);
} else {
charstring.splice(i, 1, 28, command >> 8, command & 0xff);
}
i += 2;
}
}
return charstring;
},
wrap: function wrap(name, glyphs, charstrings, subrs, properties) {
var fields = {
// major version, minor version, header size, offset size
'header': '\x01\x00\x04\x04',
'names': this.createCFFIndexHeader([name]),
'topDict': (function topDict(self) {
return function() {
var dict =
'\x00\x01\x01\x01\x30' +
'\xf8\x1b\x00' + // version
'\xf8\x1c\x01' + // Notice
'\xf8\x1d\x02' + // FullName
'\xf8\x1e\x03' + // FamilyName
'\xf8\x1f\x04' + // Weight
'\x1c\x00\x00\x10'; // Encoding
var boundingBox = properties.bbox;
for (var i = 0; i < boundingBox.length; i++)
dict += self.encodeNumber(boundingBox[i]);
dict += '\x05'; // FontBBox;
var offset = fields.header.length +
fields.names.length +
(dict.length + (4 + 4 + 7)) +
fields.strings.length +
fields.globalSubrs.length;
dict += self.encodeNumber(offset) + '\x0f'; // Charset
offset = offset + (glyphs.length * 2) + 1;
dict += self.encodeNumber(offset) + '\x11'; // Charstrings
dict += self.encodeNumber(fields.private.length);
offset = offset + fields.charstrings.length;
dict += self.encodeNumber(offset) + '\x12'; // Private
return dict;
};
})(this),
'strings': (function strings(self) {
var strings = [
'Version 0.11', // Version
'See original notice', // Notice
name, // FullName
name, // FamilyName
'Medium' // Weight
];
return self.createCFFIndexHeader(strings);
})(this),
'globalSubrs': this.createCFFIndexHeader([]),
'charset': (function charset(self) {
var charset = '\x00'; // Encoding
var count = glyphs.length;
for (var i = 0; i < count; i++) {
var index = CFFStrings.indexOf(charstrings[i].glyph.glyph);
// Some characters like asterikmath && circlecopyrt are
// missing from the original strings, for the moment let's
// map them to .notdef and see later if it cause any
// problems
if (index == -1)
index = 0;
charset += String.fromCharCode(index >> 8, index & 0xff);
}
return charset;
})(this),
'charstrings': this.createCFFIndexHeader([[0x8B, 0x0E]].concat(glyphs),
true),
'private': (function(self) {
var data =
'\x8b\x14' + // defaultWidth
'\x8b\x15'; // nominalWidth
var fieldMap = {
BlueValues: '\x06',
OtherBlues: '\x07',
FamilyBlues: '\x08',
FamilyOtherBlues: '\x09',
StemSnapH: '\x0c\x0c',
StemSnapV: '\x0c\x0d',
BlueShift: '\x0c\x0a',
BlueFuzz: '\x0c\x0b',
BlueScale: '\x0c\x09',
LanguageGroup: '\x0c\x11',
ExpansionFactor: '\x0c\x18'
};
for (var field in fieldMap) {
if (!properties.private.hasOwnProperty(field)) continue;
var value = properties.private[field];
if (IsArray(value)) {
data += self.encodeNumber(value[0]);
for (var i = 1; i < value.length; i++)
data += self.encodeNumber(value[i] - value[i - 1]);
} else {
data += self.encodeNumber(value);
}
data += fieldMap[field];
}
data += self.encodeNumber(data.length + 4) + '\x13'; // Subrs offset
return data;
})(this),
'localSubrs': this.createCFFIndexHeader(subrs, true)
};
fields.topDict = fields.topDict();
var cff = [];
for (var index in fields) {
var field = fields[index];
for (var i = 0; i < field.length; i++)
cff.push(field.charCodeAt(i));
}
return cff;
}
};
var Type2CFF = (function() {
// TODO: replace parsing code with the Type2Parser in font_utils.js
function constructor(file, properties) {
var bytes = file.getBytes();
this.bytes = bytes;
this.properties = properties;
// Other classes expect this.data to be a Javascript array
var data = [];
for (var i = 0, ii = bytes.length; i < ii; ++i)
data.push(bytes[i]);
this.data = data;
this.parse();
};
constructor.prototype = {
parse: function cff_parse() {
var header = this.parseHeader();
var nameIndex = this.parseIndex(header.endPos);
var dictIndex = this.parseIndex(nameIndex.endPos);
if (dictIndex.length != 1)
error('More than 1 font');
var stringIndex = this.parseIndex(dictIndex.endPos);
var gsubrIndex = this.parseIndex(stringIndex.endPos);
var strings = this.getStrings(stringIndex);
var baseDict = this.parseDict(dictIndex.get(0));
var topDict = this.getTopDict(baseDict, strings);
var bytes = this.bytes;
var privInfo = topDict['Private'];
var privOffset = privInfo[1], privLength = privInfo[0];
var privBytes = bytes.subarray(privOffset, privOffset + privLength);
baseDict = this.parseDict(privBytes);
var privDict = this.getPrivDict(baseDict, strings);
TODO('Parse encoding');
var charStrings = this.parseIndex(topDict['CharStrings']);
var charset = this.parseCharsets(topDict['charset'], charStrings.length,
strings);
// charstrings contains info about glyphs (one element per glyph
// containing mappings for {unicode, width})
var charstrings = this.getCharStrings(charset, charStrings,
privDict, this.properties);
// create the mapping between charstring and glyph id
var glyphIds = [];
for (var i = 0, ii = charstrings.length; i < ii; ++i) {
glyphIds.push(charstrings[i].gid);
}
this.charstrings = charstrings;
this.glyphIds = glyphIds;
},
getCharStrings: function cff_charstrings(charsets, charStrings,
privDict, properties) {
var widths = properties.widths;
var defaultWidth = privDict['defaultWidthX'];
var nominalWidth = privDict['nominalWidthX'];
var charstrings = [];
for (var i = 0, ii = charsets.length; i < ii; ++i) {
var charName = charsets[i];
var charCode = GlyphsUnicode[charName];
if (charCode) {
var width = widths[charCode] || defaultWidth;
charstrings.push({unicode: charCode, width: width, gid: i});
} else {
if (charName !== '.notdef')
warn('Cannot find unicode for glyph ' + charName);
}
}
// sort the arry by the unicode value
charstrings.sort(function(a, b) {return a.unicode - b.unicode});
return charstrings;
},
parseEncoding: function cff_parseencoding(pos) {
if (pos == 0) {
return Encodings.StandardEncoding;
} else if (pos == 1) {
return Encodings.ExpertEncoding;
}
error('not implemented encodings');
},
parseCharsets: function cff_parsecharsets(pos, length, strings) {
var bytes = this.bytes;
var format = bytes[pos++];
var charset = ['.notdef'];
// subtract 1 for the .notdef glyph
length -= 1;
switch (format) {
case 0:
for (var i = 0; i < length; ++i) {
var id = bytes[pos++];
id = (id << 8) | bytes[pos++];
charset.push(strings[id]);
}
return charset;
case 1:
while (charset.length <= length) {
var first = bytes[pos++];
first = (first << 8) | bytes[pos++];
var numLeft = bytes[pos++];
for (var i = 0; i <= numLeft; ++i)
charset.push(strings[first++]);
}
return charset;
case 2:
while (charset.length <= length) {
var first = bytes[pos++];
first = (first << 8) | bytes[pos++];
var numLeft = bytes[pos++];
numLeft = (numLeft << 8) | bytes[pos++];
for (var i = 0; i <= numLeft; ++i)
charset.push(strings[first++]);
}
return charset;
default:
error('Unknown charset format');
}
},
getPrivDict: function cff_getprivdict(baseDict, strings) {
var dict = {};
// default values
dict['defaultWidthX'] = 0;
dict['nominalWidthX'] = 0;
for (var i = 0, ii = baseDict.length; i < ii; ++i) {
var pair = baseDict[i];
var key = pair[0];
var value = pair[1];
switch (key) {
case 20:
dict['defaultWidthX'] = value[0];
case 21:
dict['nominalWidthX'] = value[0];
default:
TODO('interpret top dict key');
}
}
return dict;
},
getTopDict: function cff_gettopdict(baseDict, strings) {
var dict = {};
// default values
dict['Encoding'] = 0;
dict['charset'] = 0;
for (var i = 0, ii = baseDict.length; i < ii; ++i) {
var pair = baseDict[i];
var key = pair[0];
var value = pair[1];
switch (key) {
case 1:
dict['Notice'] = strings[value[0]];
break;
case 4:
dict['Weight'] = strings[value[0]];
break;
case 3094:
dict['BaseFontName'] = strings[value[0]];
break;
case 5:
dict['FontBBox'] = value;
break;
case 13:
dict['UniqueID'] = value[0];
break;
case 15:
dict['charset'] = value[0];
break;
case 16:
dict['Encoding'] = value[0];
break;
case 17:
dict['CharStrings'] = value[0];
break;
case 18:
dict['Private'] = value;
break;
default:
TODO('interpret top dict key');
}
}
return dict;
},
getStrings: function cff_getstrings(stringIndex) {
function bytesToString(bytesArr) {
var s = '';
for (var i = 0, ii = bytesArr.length; i < ii; ++i)
s += String.fromCharCode(bytesArr[i]);
return s;
}
var stringArray = [];
for (var i = 0, ii = CFFStrings.length; i < ii; ++i)
stringArray.push(CFFStrings[i]);
for (var i = 0, ii = stringIndex.length; i < ii; ++i)
stringArray.push(bytesToString(stringIndex.get(i)));
return stringArray;
},
parseHeader: function cff_parseHeader() {
var bytes = this.bytes;
var offset = 0;
while (bytes[offset] != 1)
++offset;
if (offset != 0) {
warning('cff data is shifted');
bytes = bytes.subarray(offset);
this.bytes = bytes;
}
return {
endPos: bytes[2],
offsetSize: bytes[3]
};
},
parseDict: function cff_parseDict(dict) {
var pos = 0;
function parseOperand() {
var value = dict[pos++];
if (value === 30) {
return parseFloatOperand(pos);
} else if (value === 28) {
value = dict[pos++];
value = (value << 8) | dict[pos++];
return value;
} else if (value === 29) {
value = dict[pos++];
value = (value << 8) | dict[pos++];
value = (value << 8) | dict[pos++];
value = (value << 8) | dict[pos++];
return value;
} else if (value <= 246) {
return value - 139;
} else if (value <= 250) {
return ((value - 247) * 256) + dict[pos++] + 108;
} else if (value <= 254) {
return -((value - 251) * 256) - dict[pos++] - 108;
} else {
error('Incorrect byte');
}
};
function parseFloatOperand() {
var str = '';
var eof = 15;
var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '.', 'E', 'E-', null, '-'];
var length = dict.length;
while (pos < length) {
var b = dict[pos++];
var b1 = b >> 4;
var b2 = b & 15;
if (b1 == eof)
break;
str += lookup[b1];
if (b2 == eof)
break;
str += lookup[b2];
}
return parseFloat(str);
};
var operands = [];
var entries = [];
var pos = 0;
var end = dict.length;
while (pos < end) {
var b = dict[pos];
if (b <= 21) {
if (b === 12) {
++pos;
var b = (b << 8) | dict[pos];
}
entries.push([b, operands]);
operands = [];
++pos;
} else {
operands.push(parseOperand());
}
}
return entries;
},
parseIndex: function cff_parseIndex(pos) {
var bytes = this.bytes;
var count = bytes[pos++] << 8 | bytes[pos++];
if (count == 0) {
var offsets = [];
var end = pos;
} else {
var offsetSize = bytes[pos++];
// add 1 for offset to determine size of last object
var startPos = pos + ((count + 1) * offsetSize) - 1;
var offsets = [];
for (var i = 0, ii = count + 1; i < ii; ++i) {
var offset = 0;
for (var j = 0; j < offsetSize; ++j) {
offset <<= 8;
offset += bytes[pos++];
}
offsets.push(startPos + offset);
}
var end = offsets[count];
}
return {
get: function index_get(index) {
if (index >= count)
return null;
var start = offsets[index];
var end = offsets[index + 1];
return bytes.subarray(start, end);
},
length: count,
endPos: end
};
}
};
return constructor;
})();
| fonts.js | /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
var isWorker = (typeof window == 'undefined');
/**
* Maximum file size of the font.
*/
var kMaxFontFileSize = 300000;
/**
* Maximum time to wait for a font to be loaded by font-face rules.
*/
var kMaxWaitForFontFace = 1000;
/**
* Hold a map of decoded fonts and of the standard fourteen Type1
* fonts and their acronyms.
*/
var stdFontMap = {
'Arial': 'Helvetica',
'Arial_Bold': 'Helvetica-Bold',
'Arial_BoldItalic': 'Helvetica-BoldOblique',
'Arial_Italic': 'Helvetica-Oblique',
'Arial_BoldItalicMT': 'Helvetica-BoldOblique',
'Arial_BoldMT': 'Helvetica-Bold',
'Arial_ItalicMT': 'Helvetica-Oblique',
'ArialMT': 'Helvetica',
'Courier_Bold': 'Courier-Bold',
'Courier_BoldItalic': 'Courier-BoldOblique',
'Courier_Italic': 'Courier-Oblique',
'CourierNew': 'Courier',
'CourierNew_Bold': 'Courier-Bold',
'CourierNew_BoldItalic': 'Courier-BoldOblique',
'CourierNew_Italic': 'Courier-Oblique',
'CourierNewPS_BoldItalicMT': 'Courier-BoldOblique',
'CourierNewPS_BoldMT': 'Courier-Bold',
'CourierNewPS_ItalicMT': 'Courier-Oblique',
'CourierNewPSMT': 'Courier',
'Helvetica_Bold': 'Helvetica-Bold',
'Helvetica_BoldItalic': 'Helvetica-BoldOblique',
'Helvetica_Italic': 'Helvetica-Oblique',
'Symbol_Bold': 'Symbol',
'Symbol_BoldItalic': 'Symbol',
'Symbol_Italic': 'Symbol',
'TimesNewRoman': 'Times-Roman',
'TimesNewRoman_Bold': 'Times-Bold',
'TimesNewRoman_BoldItalic': 'Times-BoldItalic',
'TimesNewRoman_Italic': 'Times-Italic',
'TimesNewRomanPS': 'Times-Roman',
'TimesNewRomanPS_Bold': 'Times-Bold',
'TimesNewRomanPS_BoldItalic': 'Times-BoldItalic',
'TimesNewRomanPS_BoldItalicMT': 'Times-BoldItalic',
'TimesNewRomanPS_BoldMT': 'Times-Bold',
'TimesNewRomanPS_Italic': 'Times-Italic',
'TimesNewRomanPS_ItalicMT': 'Times-Italic',
'TimesNewRomanPSMT': 'Times-Roman',
'TimesNewRomanPSMT_Bold': 'Times-Bold',
'TimesNewRomanPSMT_BoldItalic': 'Times-BoldItalic',
'TimesNewRomanPSMT_Italic': 'Times-Italic'
};
var FontMeasure = (function FontMeasure() {
var kScalePrecision = 50;
var ctx = document.createElement('canvas').getContext('2d');
ctx.scale(1 / kScalePrecision, 1);
var current;
var measureCache;
return {
setActive: function fonts_setActive(font, size) {
if (current = font) {
var sizes = current.sizes;
if (!(measureCache = sizes[size]))
measureCache = sizes[size] = Object.create(null);
} else {
measureCache = null;
}
var name = font.loadedName;
var bold = font.bold ? 'bold' : 'normal';
var italic = font.italic ? 'italic' : 'normal';
size *= kScalePrecision;
var rule = italic + ' ' + bold + ' ' + size + 'px "' + name + '"';
ctx.font = rule;
},
measureText: function fonts_measureText(text) {
var width;
if (measureCache && (width = measureCache[text]))
return width;
width = ctx.measureText(text).width / kScalePrecision;
if (measureCache)
measureCache[text] = width;
return width;
}
};
})();
var FontLoader = {
listeningForFontLoad: false,
bind: function(fonts, callback) {
function checkFontsLoaded() {
for (var i = 0; i < objs.length; i++) {
var fontObj = objs[i];
if (fontObj.loading) {
return false;
}
}
document.documentElement.removeEventListener(
'pdfjsFontLoad', checkFontsLoaded, false);
callback();
return true;
}
var rules = [], names = [], objs = [];
for (var i = 0; i < fonts.length; i++) {
var font = fonts[i];
var obj = new Font(font.name, font.file, font.properties);
objs.push(obj);
var str = '';
var data = obj.data;
if (data) {
var length = data.length;
for (var j = 0; j < length; j++)
str += String.fromCharCode(data[j]);
var rule = isWorker ? obj.bindWorker(str) : obj.bindDOM(str);
if (rule) {
rules.push(rule);
names.push(obj.loadedName);
}
}
}
this.listeningForFontLoad = false;
if (!isWorker && rules.length) {
FontLoader.prepareFontLoadEvent(rules, names, objs);
}
if (!checkFontsLoaded()) {
document.documentElement.addEventListener(
'pdfjsFontLoad', checkFontsLoaded, false);
}
return objs;
},
// Set things up so that at least one pdfjsFontLoad event is
// dispatched when all the @font-face |rules| for |names| have been
// loaded in a subdocument. It's expected that the load of |rules|
// has already started in this (outer) document, so that they should
// be ordered before the load in the subdocument.
prepareFontLoadEvent: function(rules, names, objs) {
/** Hack begin */
// There's no event when a font has finished downloading so the
// following code is a dirty hack to 'guess' when a font is
// ready. This code will be obsoleted by Mozilla bug 471915.
//
// The only reliable way to know if a font is loaded in Gecko
// (at the moment) is document.onload in a document with
// a @font-face rule defined in a "static" stylesheet. We use a
// subdocument in an <iframe>, set up properly, to know when
// our @font-face rule was loaded. However, the subdocument and
// outer document can't share CSS rules, so the inner document
// is only part of the puzzle. The second piece is an invisible
// div created in order to force loading of the @font-face in
// the *outer* document. (The font still needs to be loaded for
// its metrics, for reflow). We create the div first for the
// outer document, then create the iframe. Unless something
// goes really wonkily, we expect the @font-face for the outer
// document to be processed before the inner. That's still
// fragile, but seems to work in practice.
//
// The postMessage() hackery was added to work around chrome bug
// 82402.
var div = document.createElement('div');
div.setAttribute('style',
'visibility: hidden;' +
'width: 10px; height: 10px;' +
'position: absolute; top: 0px; left: 0px;');
var html = '';
for (var i = 0; i < names.length; ++i) {
html += '<span style="font-family:' + names[i] + '">Hi</span>';
}
div.innerHTML = html;
document.body.appendChild(div);
if (!this.listeningForFontLoad) {
window.addEventListener(
'message',
function(e) {
var fontNames = JSON.parse(e.data);
for (var i = 0; i < objs.length; ++i) {
var font = objs[i];
font.loading = false;
}
var evt = document.createEvent('Events');
evt.initEvent('pdfjsFontLoad', true, false);
document.documentElement.dispatchEvent(evt);
},
false);
this.listeningForFontLoad = true;
}
// XXX we should have a time-out here too, and maybe fire
// pdfjsFontLoadFailed?
var src = '<!DOCTYPE HTML><html><head>';
src += '<style type="text/css">';
for (var i = 0; i < rules.length; ++i) {
src += rules[i];
}
src += '</style>';
src += '<script type="application/javascript">';
var fontNamesArray = '';
for (var i = 0; i < names.length; ++i) {
fontNamesArray += '"' + names[i] + '", ';
}
src += ' var fontNames=[' + fontNamesArray + '];\n';
src += ' window.onload = function () {\n';
src += ' top.postMessage(JSON.stringify(fontNames), "*");\n';
src += ' }';
src += '</script></head><body>';
for (var i = 0; i < names.length; ++i) {
src += '<p style="font-family:\'' + names[i] + '\'">Hi</p>';
}
src += '</body></html>';
var frame = document.createElement('iframe');
frame.src = 'data:text/html,' + src;
frame.setAttribute('style',
'visibility: hidden;' +
'width: 10px; height: 10px;' +
'position: absolute; top: 0px; left: 0px;');
document.body.appendChild(frame);
/** Hack end */
}
};
var UnicodeRanges = [
{ 'begin': 0x0000, 'end': 0x007F }, // Basic Latin
{ 'begin': 0x0080, 'end': 0x00FF }, // Latin-1 Supplement
{ 'begin': 0x0100, 'end': 0x017F }, // Latin Extended-A
{ 'begin': 0x0180, 'end': 0x024F }, // Latin Extended-B
{ 'begin': 0x0250, 'end': 0x02AF }, // IPA Extensions
{ 'begin': 0x02B0, 'end': 0x02FF }, // Spacing Modifier Letters
{ 'begin': 0x0300, 'end': 0x036F }, // Combining Diacritical Marks
{ 'begin': 0x0370, 'end': 0x03FF }, // Greek and Coptic
{ 'begin': 0x2C80, 'end': 0x2CFF }, // Coptic
{ 'begin': 0x0400, 'end': 0x04FF }, // Cyrillic
{ 'begin': 0x0530, 'end': 0x058F }, // Armenian
{ 'begin': 0x0590, 'end': 0x05FF }, // Hebrew
{ 'begin': 0xA500, 'end': 0xA63F }, // Vai
{ 'begin': 0x0600, 'end': 0x06FF }, // Arabic
{ 'begin': 0x07C0, 'end': 0x07FF }, // NKo
{ 'begin': 0x0900, 'end': 0x097F }, // Devanagari
{ 'begin': 0x0980, 'end': 0x09FF }, // Bengali
{ 'begin': 0x0A00, 'end': 0x0A7F }, // Gurmukhi
{ 'begin': 0x0A80, 'end': 0x0AFF }, // Gujarati
{ 'begin': 0x0B00, 'end': 0x0B7F }, // Oriya
{ 'begin': 0x0B80, 'end': 0x0BFF }, // Tamil
{ 'begin': 0x0C00, 'end': 0x0C7F }, // Telugu
{ 'begin': 0x0C80, 'end': 0x0CFF }, // Kannada
{ 'begin': 0x0D00, 'end': 0x0D7F }, // Malayalam
{ 'begin': 0x0E00, 'end': 0x0E7F }, // Thai
{ 'begin': 0x0E80, 'end': 0x0EFF }, // Lao
{ 'begin': 0x10A0, 'end': 0x10FF }, // Georgian
{ 'begin': 0x1B00, 'end': 0x1B7F }, // Balinese
{ 'begin': 0x1100, 'end': 0x11FF }, // Hangul Jamo
{ 'begin': 0x1E00, 'end': 0x1EFF }, // Latin Extended Additional
{ 'begin': 0x1F00, 'end': 0x1FFF }, // Greek Extended
{ 'begin': 0x2000, 'end': 0x206F }, // General Punctuation
{ 'begin': 0x2070, 'end': 0x209F }, // Superscripts And Subscripts
{ 'begin': 0x20A0, 'end': 0x20CF }, // Currency Symbol
{ 'begin': 0x20D0, 'end': 0x20FF }, // Combining Diacritical Marks For Symbols
{ 'begin': 0x2100, 'end': 0x214F }, // Letterlike Symbols
{ 'begin': 0x2150, 'end': 0x218F }, // Number Forms
{ 'begin': 0x2190, 'end': 0x21FF }, // Arrows
{ 'begin': 0x2200, 'end': 0x22FF }, // Mathematical Operators
{ 'begin': 0x2300, 'end': 0x23FF }, // Miscellaneous Technical
{ 'begin': 0x2400, 'end': 0x243F }, // Control Pictures
{ 'begin': 0x2440, 'end': 0x245F }, // Optical Character Recognition
{ 'begin': 0x2460, 'end': 0x24FF }, // Enclosed Alphanumerics
{ 'begin': 0x2500, 'end': 0x257F }, // Box Drawing
{ 'begin': 0x2580, 'end': 0x259F }, // Block Elements
{ 'begin': 0x25A0, 'end': 0x25FF }, // Geometric Shapes
{ 'begin': 0x2600, 'end': 0x26FF }, // Miscellaneous Symbols
{ 'begin': 0x2700, 'end': 0x27BF }, // Dingbats
{ 'begin': 0x3000, 'end': 0x303F }, // CJK Symbols And Punctuation
{ 'begin': 0x3040, 'end': 0x309F }, // Hiragana
{ 'begin': 0x30A0, 'end': 0x30FF }, // Katakana
{ 'begin': 0x3100, 'end': 0x312F }, // Bopomofo
{ 'begin': 0x3130, 'end': 0x318F }, // Hangul Compatibility Jamo
{ 'begin': 0xA840, 'end': 0xA87F }, // Phags-pa
{ 'begin': 0x3200, 'end': 0x32FF }, // Enclosed CJK Letters And Months
{ 'begin': 0x3300, 'end': 0x33FF }, // CJK Compatibility
{ 'begin': 0xAC00, 'end': 0xD7AF }, // Hangul Syllables
{ 'begin': 0xD800, 'end': 0xDFFF }, // Non-Plane 0 *
{ 'begin': 0x10900, 'end': 0x1091F }, // Phoenicia
{ 'begin': 0x4E00, 'end': 0x9FFF }, // CJK Unified Ideographs
{ 'begin': 0xE000, 'end': 0xF8FF }, // Private Use Area (plane 0)
{ 'begin': 0x31C0, 'end': 0x31EF }, // CJK Strokes
{ 'begin': 0xFB00, 'end': 0xFB4F }, // Alphabetic Presentation Forms
{ 'begin': 0xFB50, 'end': 0xFDFF }, // Arabic Presentation Forms-A
{ 'begin': 0xFE20, 'end': 0xFE2F }, // Combining Half Marks
{ 'begin': 0xFE10, 'end': 0xFE1F }, // Vertical Forms
{ 'begin': 0xFE50, 'end': 0xFE6F }, // Small Form Variants
{ 'begin': 0xFE70, 'end': 0xFEFF }, // Arabic Presentation Forms-B
{ 'begin': 0xFF00, 'end': 0xFFEF }, // Halfwidth And Fullwidth Forms
{ 'begin': 0xFFF0, 'end': 0xFFFF }, // Specials
{ 'begin': 0x0F00, 'end': 0x0FFF }, // Tibetan
{ 'begin': 0x0700, 'end': 0x074F }, // Syriac
{ 'begin': 0x0780, 'end': 0x07BF }, // Thaana
{ 'begin': 0x0D80, 'end': 0x0DFF }, // Sinhala
{ 'begin': 0x1000, 'end': 0x109F }, // Myanmar
{ 'begin': 0x1200, 'end': 0x137F }, // Ethiopic
{ 'begin': 0x13A0, 'end': 0x13FF }, // Cherokee
{ 'begin': 0x1400, 'end': 0x167F }, // Unified Canadian Aboriginal Syllabics
{ 'begin': 0x1680, 'end': 0x169F }, // Ogham
{ 'begin': 0x16A0, 'end': 0x16FF }, // Runic
{ 'begin': 0x1780, 'end': 0x17FF }, // Khmer
{ 'begin': 0x1800, 'end': 0x18AF }, // Mongolian
{ 'begin': 0x2800, 'end': 0x28FF }, // Braille Patterns
{ 'begin': 0xA000, 'end': 0xA48F }, // Yi Syllables
{ 'begin': 0x1700, 'end': 0x171F }, // Tagalog
{ 'begin': 0x10300, 'end': 0x1032F }, // Old Italic
{ 'begin': 0x10330, 'end': 0x1034F }, // Gothic
{ 'begin': 0x10400, 'end': 0x1044F }, // Deseret
{ 'begin': 0x1D000, 'end': 0x1D0FF }, // Byzantine Musical Symbols
{ 'begin': 0x1D400, 'end': 0x1D7FF }, // Mathematical Alphanumeric Symbols
{ 'begin': 0xFF000, 'end': 0xFFFFD }, // Private Use (plane 15)
{ 'begin': 0xFE00, 'end': 0xFE0F }, // Variation Selectors
{ 'begin': 0xE0000, 'end': 0xE007F }, // Tags
{ 'begin': 0x1900, 'end': 0x194F }, // Limbu
{ 'begin': 0x1950, 'end': 0x197F }, // Tai Le
{ 'begin': 0x1980, 'end': 0x19DF }, // New Tai Lue
{ 'begin': 0x1A00, 'end': 0x1A1F }, // Buginese
{ 'begin': 0x2C00, 'end': 0x2C5F }, // Glagolitic
{ 'begin': 0x2D30, 'end': 0x2D7F }, // Tifinagh
{ 'begin': 0x4DC0, 'end': 0x4DFF }, // Yijing Hexagram Symbols
{ 'begin': 0xA800, 'end': 0xA82F }, // Syloti Nagri
{ 'begin': 0x10000, 'end': 0x1007F }, // Linear B Syllabary
{ 'begin': 0x10140, 'end': 0x1018F }, // Ancient Greek Numbers
{ 'begin': 0x10380, 'end': 0x1039F }, // Ugaritic
{ 'begin': 0x103A0, 'end': 0x103DF }, // Old Persian
{ 'begin': 0x10450, 'end': 0x1047F }, // Shavian
{ 'begin': 0x10480, 'end': 0x104AF }, // Osmanya
{ 'begin': 0x10800, 'end': 0x1083F }, // Cypriot Syllabary
{ 'begin': 0x10A00, 'end': 0x10A5F }, // Kharoshthi
{ 'begin': 0x1D300, 'end': 0x1D35F }, // Tai Xuan Jing Symbols
{ 'begin': 0x12000, 'end': 0x123FF }, // Cuneiform
{ 'begin': 0x1D360, 'end': 0x1D37F }, // Counting Rod Numerals
{ 'begin': 0x1B80, 'end': 0x1BBF }, // Sundanese
{ 'begin': 0x1C00, 'end': 0x1C4F }, // Lepcha
{ 'begin': 0x1C50, 'end': 0x1C7F }, // Ol Chiki
{ 'begin': 0xA880, 'end': 0xA8DF }, // Saurashtra
{ 'begin': 0xA900, 'end': 0xA92F }, // Kayah Li
{ 'begin': 0xA930, 'end': 0xA95F }, // Rejang
{ 'begin': 0xAA00, 'end': 0xAA5F }, // Cham
{ 'begin': 0x10190, 'end': 0x101CF }, // Ancient Symbols
{ 'begin': 0x101D0, 'end': 0x101FF }, // Phaistos Disc
{ 'begin': 0x102A0, 'end': 0x102DF }, // Carian
{ 'begin': 0x1F030, 'end': 0x1F09F } // Domino Tiles
];
function getUnicodeRangeFor(value) {
for (var i = 0; i < UnicodeRanges.length; i++) {
var range = UnicodeRanges[i];
if (value >= range.begin && value < range.end)
return i;
}
return -1;
}
/**
* 'Font' is the class the outside world should use, it encapsulate all the font
* decoding logics whatever type it is (assuming the font type is supported).
*
* For example to read a Type1 font and to attach it to the document:
* var type1Font = new Font("MyFontName", binaryFile, propertiesObject);
* type1Font.bind();
*/
var Font = (function Font() {
var constructor = function font_constructor(name, file, properties) {
this.name = name;
this.encoding = properties.encoding;
this.sizes = [];
// If the font is to be ignored, register it like an already loaded font
// to avoid the cost of waiting for it be be loaded by the platform.
if (properties.ignore) {
this.loadedName = 'sans-serif';
this.loading = false;
return;
}
if (!file) {
// The file data is not specified. Trying to fix the font name
// to be used with the canvas.font.
var fontName = stdFontMap[name] || name.replace('_', '-');
this.bold = (fontName.indexOf('Bold') != -1);
this.italic = (fontName.indexOf('Oblique') != -1) ||
(fontName.indexOf('Italic') != -1);
this.loadedName = fontName.split('-')[0];
this.loading = false;
this.charsToUnicode = function(s) {
return s;
};
return;
}
var data;
switch (properties.type) {
case 'Type1':
case 'CIDFontType0':
this.mimetype = 'font/opentype';
var subtype = properties.subtype;
if (subtype === 'Type1C') {
var cff = new Type2CFF(file, properties);
} else {
var cff = new CFF(name, file, properties);
}
// Wrap the CFF data inside an OTF font file
data = this.convert(name, cff, properties);
break;
case 'TrueType':
case 'CIDFontType2':
this.mimetype = 'font/opentype';
// Repair the TrueType file if it is can be damaged in the point of
// view of the sanitizer
data = this.checkAndRepair(name, file, properties);
break;
default:
warn('Font ' + properties.type + ' is not supported');
break;
}
this.data = data;
this.type = properties.type;
this.textMatrix = properties.textMatrix;
this.loadedName = getUniqueName();
this.compositeFont = properties.compositeFont;
this.loading = true;
};
var numFonts = 0;
function getUniqueName() {
return 'pdfFont' + numFonts++;
}
function stringToArray(str) {
var array = [];
for (var i = 0; i < str.length; ++i)
array[i] = str.charCodeAt(i);
return array;
};
function int16(bytes) {
return (bytes[0] << 8) + (bytes[1] & 0xff);
};
function int32(bytes) {
return (bytes[0] << 24) + (bytes[1] << 16) +
(bytes[2] << 8) + (bytes[3] & 0xff);
};
function getMaxPower2(number) {
var maxPower = 0;
var value = number;
while (value >= 2) {
value /= 2;
maxPower++;
}
value = 2;
for (var i = 1; i < maxPower; i++)
value *= 2;
return value;
};
function string16(value) {
return String.fromCharCode((value >> 8) & 0xff) +
String.fromCharCode(value & 0xff);
};
function string32(value) {
return String.fromCharCode((value >> 24) & 0xff) +
String.fromCharCode((value >> 16) & 0xff) +
String.fromCharCode((value >> 8) & 0xff) +
String.fromCharCode(value & 0xff);
};
function createOpenTypeHeader(sfnt, file, offsets, numTables) {
// sfnt version (4 bytes)
var header = sfnt;
// numTables (2 bytes)
header += string16(numTables);
// searchRange (2 bytes)
var tablesMaxPower2 = getMaxPower2(numTables);
var searchRange = tablesMaxPower2 * 16;
header += string16(searchRange);
// entrySelector (2 bytes)
header += string16(Math.log(tablesMaxPower2) / Math.log(2));
// rangeShift (2 bytes)
header += string16(numTables * 16 - searchRange);
file.set(stringToArray(header), offsets.currentOffset);
offsets.currentOffset += header.length;
offsets.virtualOffset += header.length;
};
function createTableEntry(file, offsets, tag, data) {
// offset
var offset = offsets.virtualOffset;
// length
var length = data.length;
// Per spec tables must be 4-bytes align so add padding as needed
while (data.length & 3)
data.push(0x00);
while (offsets.virtualOffset & 3)
offsets.virtualOffset++;
// checksum
var checksum = 0, n = data.length;
for (var i = 0; i < n; i += 4)
checksum = (checksum + int32([data[i], data[i + 1], data[i + 2],
data[i + 3]])) | 0;
var tableEntry = (tag + string32(checksum) +
string32(offset) + string32(length));
tableEntry = stringToArray(tableEntry);
file.set(tableEntry, offsets.currentOffset);
offsets.currentOffset += tableEntry.length;
offsets.virtualOffset += data.length;
};
function getRanges(glyphs) {
// Array.sort() sorts by characters, not numerically, so convert to an
// array of characters.
var codes = [];
var length = glyphs.length;
for (var n = 0; n < length; ++n)
codes.push(String.fromCharCode(glyphs[n].unicode));
codes.sort();
// Split the sorted codes into ranges.
var ranges = [];
for (var n = 0; n < length; ) {
var start = codes[n++].charCodeAt(0);
var end = start;
while (n < length && end + 1 == codes[n].charCodeAt(0)) {
++end;
++n;
}
ranges.push([start, end]);
}
return ranges;
};
function createCMapTable(glyphs, deltas) {
var ranges = getRanges(glyphs);
var numTables = 1;
var cmap = '\x00\x00' + // version
string16(numTables) + // numTables
'\x00\x03' + // platformID
'\x00\x01' + // encodingID
string32(4 + numTables * 8); // start of the table record
var segCount = ranges.length + 1;
var segCount2 = segCount * 2;
var searchRange = getMaxPower2(segCount) * 2;
var searchEntry = Math.log(segCount) / Math.log(2);
var rangeShift = 2 * segCount - searchRange;
// Fill up the 4 parallel arrays describing the segments.
var startCount = '';
var endCount = '';
var idDeltas = '';
var idRangeOffsets = '';
var glyphsIds = '';
var bias = 0;
for (var i = 0; i < segCount - 1; i++) {
var range = ranges[i];
var start = range[0];
var end = range[1];
var offset = (segCount - i) * 2 + bias * 2;
bias += (end - start + 1);
startCount += string16(start);
endCount += string16(end);
idDeltas += string16(0);
idRangeOffsets += string16(offset);
}
for (var i = 0; i < glyphs.length; i++)
glyphsIds += string16(deltas ? deltas[i] : i + 1);
endCount += '\xFF\xFF';
startCount += '\xFF\xFF';
idDeltas += '\x00\x01';
idRangeOffsets += '\x00\x00';
var format314 = '\x00\x00' + // language
string16(segCount2) +
string16(searchRange) +
string16(searchEntry) +
string16(rangeShift) +
endCount + '\x00\x00' + startCount +
idDeltas + idRangeOffsets + glyphsIds;
return stringToArray(cmap +
'\x00\x04' + // format
string16(format314.length + 4) + // length
format314);
};
function createOS2Table(properties) {
var ulUnicodeRange1 = 0;
var ulUnicodeRange2 = 0;
var ulUnicodeRange3 = 0;
var ulUnicodeRange4 = 0;
var charset = properties.charset;
if (charset && charset.length) {
var firstCharIndex = null;
var lastCharIndex = 0;
for (var i = 0; i < charset.length; i++) {
var code = GlyphsUnicode[charset[i]];
if (firstCharIndex > code || !firstCharIndex)
firstCharIndex = code;
if (lastCharIndex < code)
lastCharIndex = code;
var position = getUnicodeRangeFor(code);
if (position < 32) {
ulUnicodeRange1 |= 1 << position;
} else if (position < 64) {
ulUnicodeRange2 |= 1 << position - 32;
} else if (position < 96) {
ulUnicodeRange3 |= 1 << position - 64;
} else if (position < 123) {
ulUnicodeRange4 |= 1 << position - 96;
} else {
error('Unicode ranges Bits > 123 are reserved for internal usage');
}
}
}
return '\x00\x03' + // version
'\x02\x24' + // xAvgCharWidth
'\x01\xF4' + // usWeightClass
'\x00\x05' + // usWidthClass
'\x00\x00' + // fstype (0 to let the font loads via font-face on IE)
'\x02\x8A' + // ySubscriptXSize
'\x02\xBB' + // ySubscriptYSize
'\x00\x00' + // ySubscriptXOffset
'\x00\x8C' + // ySubscriptYOffset
'\x02\x8A' + // ySuperScriptXSize
'\x02\xBB' + // ySuperScriptYSize
'\x00\x00' + // ySuperScriptXOffset
'\x01\xDF' + // ySuperScriptYOffset
'\x00\x31' + // yStrikeOutSize
'\x01\x02' + // yStrikeOutPosition
'\x00\x00' + // sFamilyClass
'\x00\x00\x06' +
String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) +
'\x00\x00\x00\x00\x00\x00' + // Panose
string32(ulUnicodeRange1) + // ulUnicodeRange1 (Bits 0-31)
string32(ulUnicodeRange2) + // ulUnicodeRange2 (Bits 32-63)
string32(ulUnicodeRange3) + // ulUnicodeRange3 (Bits 64-95)
string32(ulUnicodeRange4) + // ulUnicodeRange4 (Bits 96-127)
'\x2A\x32\x31\x2A' + // achVendID
string16(properties.italicAngle ? 1 : 0) + // fsSelection
string16(firstCharIndex ||
properties.firstChar) + // usFirstCharIndex
string16(lastCharIndex || properties.lastChar) + // usLastCharIndex
string16(properties.ascent) + // sTypoAscender
string16(properties.descent) + // sTypoDescender
'\x00\x64' + // sTypoLineGap (7%-10% of the unitsPerEM value)
string16(properties.ascent) + // usWinAscent
string16(-properties.descent) + // usWinDescent
'\x00\x00\x00\x00' + // ulCodePageRange1 (Bits 0-31)
'\x00\x00\x00\x00' + // ulCodePageRange2 (Bits 32-63)
string16(properties.xHeight) + // sxHeight
string16(properties.capHeight) + // sCapHeight
string16(0) + // usDefaultChar
string16(firstCharIndex || properties.firstChar) + // usBreakChar
'\x00\x03'; // usMaxContext
};
function createPostTable(properties) {
var angle = Math.floor(properties.italicAngle * (Math.pow(2, 16)));
return '\x00\x03\x00\x00' + // Version number
string32(angle) + // italicAngle
'\x00\x00' + // underlinePosition
'\x00\x00' + // underlineThickness
string32(properties.fixedPitch) + // isFixedPitch
'\x00\x00\x00\x00' + // minMemType42
'\x00\x00\x00\x00' + // maxMemType42
'\x00\x00\x00\x00' + // minMemType1
'\x00\x00\x00\x00'; // maxMemType1
};
function createNameTable(name) {
var strings = [
'Original licence', // 0.Copyright
name, // 1.Font family
'Unknown', // 2.Font subfamily (font weight)
'uniqueID', // 3.Unique ID
name, // 4.Full font name
'Version 0.11', // 5.Version
'', // 6.Postscript name
'Unknown', // 7.Trademark
'Unknown', // 8.Manufacturer
'Unknown' // 9.Designer
];
// Mac want 1-byte per character strings while Windows want
// 2-bytes per character, so duplicate the names table
var stringsUnicode = [];
for (var i = 0; i < strings.length; i++) {
var str = strings[i];
var strUnicode = '';
for (var j = 0; j < str.length; j++)
strUnicode += string16(str.charCodeAt(j));
stringsUnicode.push(strUnicode);
}
var names = [strings, stringsUnicode];
var platforms = ['\x00\x01', '\x00\x03'];
var encodings = ['\x00\x00', '\x00\x01'];
var languages = ['\x00\x00', '\x04\x09'];
var namesRecordCount = strings.length * platforms.length;
var nameTable =
'\x00\x00' + // format
string16(namesRecordCount) + // Number of names Record
string16(namesRecordCount * 12 + 6); // Storage
// Build the name records field
var strOffset = 0;
for (var i = 0; i < platforms.length; i++) {
var strs = names[i];
for (var j = 0; j < strs.length; j++) {
var str = strs[j];
var nameRecord =
platforms[i] + // platform ID
encodings[i] + // encoding ID
languages[i] + // language ID
string16(j) + // name ID
string16(str.length) +
string16(strOffset);
nameTable += nameRecord;
strOffset += str.length;
}
}
nameTable += strings.join('') + stringsUnicode.join('');
return nameTable;
}
constructor.prototype = {
name: null,
font: null,
mimetype: null,
encoding: null,
checkAndRepair: function font_checkAndRepair(name, font, properties) {
function readTableEntry(file) {
// tag
var tag = file.getBytes(4);
tag = String.fromCharCode(tag[0]) +
String.fromCharCode(tag[1]) +
String.fromCharCode(tag[2]) +
String.fromCharCode(tag[3]);
var checksum = int32(file.getBytes(4));
var offset = int32(file.getBytes(4));
var length = int32(file.getBytes(4));
// Read the table associated data
var previousPosition = file.pos;
file.pos = file.start ? file.start : 0;
file.skip(offset);
var data = file.getBytes(length);
file.pos = previousPosition;
if (tag == 'head')
// clearing checksum adjustment
data[8] = data[9] = data[10] = data[11] = 0;
return {
tag: tag,
checksum: checksum,
length: length,
offset: offset,
data: data
};
};
function readOpenTypeHeader(ttf) {
return {
version: ttf.getBytes(4),
numTables: int16(ttf.getBytes(2)),
searchRange: int16(ttf.getBytes(2)),
entrySelector: int16(ttf.getBytes(2)),
rangeShift: int16(ttf.getBytes(2))
};
};
function replaceCMapTable(cmap, font, properties) {
var start = (font.start ? font.start : 0) + cmap.offset;
font.pos = start;
var version = int16(font.getBytes(2));
var numRecords = int16(font.getBytes(2));
var records = [];
for (var i = 0; i < numRecords; i++) {
records.push({
platformID: int16(font.getBytes(2)),
encodingID: int16(font.getBytes(2)),
offset: int32(font.getBytes(4))
});
}
var encoding = properties.encoding;
var charset = properties.charset;
for (var i = 0; i < numRecords; i++) {
var table = records[i];
font.pos = start + table.offset;
var format = int16(font.getBytes(2));
var length = int16(font.getBytes(2));
var language = int16(font.getBytes(2));
if (format == 0) {
// Characters below 0x20 are controls characters that are hardcoded
// into the platform so if some characters in the font are assigned
// under this limit they will not be displayed so let's rewrite the
// CMap.
var glyphs = [];
var deltas = [];
for (var j = 0; j < 256; j++) {
var index = font.getByte();
if (index) {
deltas.push(index);
glyphs.push({ unicode: j });
}
}
var rewrite = false;
for (var code in encoding) {
if (code < 0x20 && encoding[code])
rewrite = true;
if (rewrite)
encoding[code] = parseInt(code) + 0x1F;
}
if (rewrite) {
for (var j = 0; j < glyphs.length; j++) {
glyphs[j].unicode += 0x1F;
}
}
cmap.data = createCMapTable(glyphs, deltas);
} else if (format == 6 && numRecords == 1 && !encoding.empty) {
// Format 0 alone is not allowed by the sanitizer so let's rewrite
// that to a 3-1-4 Unicode BMP table
TODO('Use an other source of informations than ' +
'charset here, it is not reliable');
var glyphs = [];
for (var j = 0; j < charset.length; j++) {
glyphs.push({
unicode: GlyphsUnicode[charset[j]] || 0
});
}
cmap.data = createCMapTable(glyphs);
} else if (format == 6 && numRecords == 1) {
// Format 6 is a 2-bytes dense mapping, which means the font data
// lives glue together even if they are pretty far in the unicode
// table. (This looks weird, so I can have missed something), this
// works on Linux but seems to fails on Mac so let's rewrite the
// cmap table to a 3-1-4 style
var firstCode = int16(font.getBytes(2));
var entryCount = int16(font.getBytes(2));
var glyphs = [];
var min = 0xffff, max = 0;
for (var j = 0; j < entryCount; j++) {
var charcode = int16(font.getBytes(2));
glyphs.push(charcode);
if (charcode < min)
min = charcode;
if (charcode > max)
max = charcode;
}
// Since Format 6 is a dense array, check for gaps
for (var j = min; j < max; j++) {
if (glyphs.indexOf(j) == -1)
glyphs.push(j);
}
for (var j = 0; j < glyphs.length; j++)
glyphs[j] = { unicode: glyphs[j] + firstCode };
var ranges = getRanges(glyphs);
assert(ranges.length == 1, 'Got ' + ranges.length +
' ranges in a dense array');
var denseRange = ranges[0];
var start = denseRange[0];
var end = denseRange[1];
var index = firstCode;
for (var j = start; j <= end; j++)
encoding[index++] = glyphs[j - firstCode - 1].unicode;
cmap.data = createCMapTable(glyphs);
}
}
};
// Check that required tables are present
var requiredTables = ['OS/2', 'cmap', 'head', 'hhea',
'hmtx', 'maxp', 'name', 'post'];
var header = readOpenTypeHeader(font);
var numTables = header.numTables;
var cmap, maxp, hhea, hmtx;
var tables = [];
for (var i = 0; i < numTables; i++) {
var table = readTableEntry(font);
var index = requiredTables.indexOf(table.tag);
if (index != -1) {
if (table.tag == 'cmap')
cmap = table;
else if (table.tag == 'maxp')
maxp = table;
else if (table.tag == 'hhea')
hhea = table;
else if (table.tag == 'hmtx')
hmtx = table;
requiredTables.splice(index, 1);
}
tables.push(table);
}
// Create a new file to hold the new version of our truetype with a new
// header and new offsets
var ttf = new Uint8Array(kMaxFontFileSize);
// The offsets object holds at the same time a representation of where
// to write the table entry information about a table and another offset
// representing the offset where to put the actual data of a particular
// table
var numTables = header.numTables + requiredTables.length;
var offsets = {
currentOffset: 0,
virtualOffset: numTables * (4 * 4)
};
// The new numbers of tables will be the last one plus the num
// of missing tables
createOpenTypeHeader('\x00\x01\x00\x00', ttf, offsets, numTables);
if (requiredTables.indexOf('OS/2') != -1) {
tables.push({
tag: 'OS/2',
data: stringToArray(createOS2Table(properties))
});
}
// Ensure the hmtx tables contains an advance width and a sidebearing
// for the number of glyphs declared in the maxp table
font.pos = (font.start ? font.start : 0) + maxp.offset;
var version = int16(font.getBytes(4));
var numGlyphs = int16(font.getBytes(2));
font.pos = (font.start ? font.start : 0) + hhea.offset;
font.pos += hhea.length - 2;
var numOfHMetrics = int16(font.getBytes(2));
var numOfSidebearings = numGlyphs - numOfHMetrics;
var numMissing = numOfSidebearings -
((hmtx.length - numOfHMetrics * 4) >> 1);
if (numMissing > 0) {
font.pos = (font.start ? font.start : 0) + hmtx.offset;
var metrics = '';
for (var i = 0; i < hmtx.length; i++)
metrics += String.fromCharCode(font.getByte());
for (var i = 0; i < numMissing; i++)
metrics += '\x00\x00';
hmtx.data = stringToArray(metrics);
}
// Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth
// Sometimes it's 0. That needs to be fixed
if (hhea.data[10] == 0 && hhea.data[11] == 0) {
hhea.data[10] = 0xFF;
hhea.data[11] = 0xFF;
}
// Replace the old CMAP table with a shiny new one
if (properties.type == 'CIDFontType2') {
// Type2 composite fonts map characters directly to glyphs so the cmap
// table must be replaced.
// canvas fillText will reencode some characters even if the font has a
// glyph at that position - e.g. newline is converted to a space and U+00AD
// (soft hypen) is not drawn.
// So, offset all the glyphs by 0xFF to avoid these cases and use
// the encoding to map incoming characters to the new glyph positions
var glyphs = [];
var encoding = properties.encoding;
for (var i = 1; i < numGlyphs; i++) {
glyphs.push({ unicode: i + 0xFF });
}
if ('undefined' == typeof(encoding[0])) {
// the font is directly characters to glyphs with no encoding
// so create an identity encoding
for (i = 0; i < numGlyphs; i++)
encoding[i] = i + 0xFF;
} else {
for (var i in encoding)
encoding[i] = encoding[i] + 0xFF;
}
if (!cmap) {
cmap = {
tag: 'cmap',
data: null
};
tables.push(cmap);
}
cmap.data = createCMapTable(glyphs);
} else {
replaceCMapTable(cmap, font, properties);
}
// Rewrite the 'post' table if needed
if (requiredTables.indexOf('post') != -1) {
tables.push({
tag: 'post',
data: stringToArray(createPostTable(properties))
});
}
// Rewrite the 'name' table if needed
if (requiredTables.indexOf('name') != -1) {
tables.push({
tag: 'name',
data: stringToArray(createNameTable(this.name))
});
}
// Tables needs to be written by ascendant alphabetic order
tables.sort(function tables_sort(a, b) {
return (a.tag > b.tag) - (a.tag < b.tag);
});
// rewrite the tables but tweak offsets
for (var i = 0; i < tables.length; i++) {
var table = tables[i];
var data = [];
var tableData = table.data;
for (var j = 0; j < tableData.length; j++)
data.push(tableData[j]);
createTableEntry(ttf, offsets, table.tag, data);
}
// Add the table datas
for (var i = 0; i < tables.length; i++) {
var table = tables[i];
var tableData = table.data;
ttf.set(tableData, offsets.currentOffset);
offsets.currentOffset += tableData.length;
// 4-byte aligned data
while (offsets.currentOffset & 3)
offsets.currentOffset++;
}
var fontData = [];
for (var i = 0; i < offsets.currentOffset; i++)
fontData.push(ttf[i]);
return fontData;
},
convert: function font_convert(fontName, font, properties) {
function isFixedPitch(glyphs) {
for (var i = 0; i < glyphs.length - 1; i++) {
if (glyphs[i] != glyphs[i + 1])
return false;
}
return true;
};
// The offsets object holds at the same time a representation of where
// to write the table entry information about a table and another offset
// representing the offset where to draw the actual data of a particular
// table
var kRequiredTablesCount = 9;
var offsets = {
currentOffset: 0,
virtualOffset: 9 * (4 * 4)
};
var otf = new Uint8Array(kMaxFontFileSize);
createOpenTypeHeader('\x4F\x54\x54\x4F', otf, offsets, 9);
var charstrings = font.charstrings;
properties.fixedPitch = isFixedPitch(charstrings);
var fields = {
// PostScript Font Program
'CFF ': font.data,
// OS/2 and Windows Specific metrics
'OS/2': stringToArray(createOS2Table(properties)),
// Character to glyphs mapping
'cmap': createCMapTable(charstrings.slice(), font.glyphIds),
// Font header
'head': (function() {
return stringToArray(
'\x00\x01\x00\x00' + // Version number
'\x00\x00\x10\x00' + // fontRevision
'\x00\x00\x00\x00' + // checksumAdjustement
'\x5F\x0F\x3C\xF5' + // magicNumber
'\x00\x00' + // Flags
'\x03\xE8' + // unitsPerEM (defaulting to 1000)
'\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date
'\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date
'\x00\x00' + // xMin
string16(properties.descent) + // yMin
'\x0F\xFF' + // xMax
string16(properties.ascent) + // yMax
string16(properties.italicAngle ? 2 : 0) + // macStyle
'\x00\x11' + // lowestRecPPEM
'\x00\x00' + // fontDirectionHint
'\x00\x00' + // indexToLocFormat
'\x00\x00'); // glyphDataFormat
})(),
// Horizontal header
'hhea': (function() {
return stringToArray(
'\x00\x01\x00\x00' + // Version number
string16(properties.ascent) + // Typographic Ascent
string16(properties.descent) + // Typographic Descent
'\x00\x00' + // Line Gap
'\xFF\xFF' + // advanceWidthMax
'\x00\x00' + // minLeftSidebearing
'\x00\x00' + // minRightSidebearing
'\x00\x00' + // xMaxExtent
string16(properties.capHeight) + // caretSlopeRise
string16(Math.tan(properties.italicAngle) *
properties.xHeight) + // caretSlopeRun
'\x00\x00' + // caretOffset
'\x00\x00' + // -reserved-
'\x00\x00' + // -reserved-
'\x00\x00' + // -reserved-
'\x00\x00' + // -reserved-
'\x00\x00' + // metricDataFormat
string16(charstrings.length + 1)); // Number of HMetrics
})(),
// Horizontal metrics
'hmtx': (function() {
var hmtx = '\x00\x00\x00\x00'; // Fake .notdef
for (var i = 0; i < charstrings.length; i++) {
hmtx += string16(charstrings[i].width) + string16(0);
}
return stringToArray(hmtx);
})(),
// Maximum profile
'maxp': (function() {
return stringToArray(
'\x00\x00\x50\x00' + // Version number
string16(charstrings.length + 1)); // Num of glyphs
})(),
// Naming tables
'name': stringToArray(createNameTable(fontName)),
// PostScript informations
'post': stringToArray(createPostTable(properties))
};
for (var field in fields)
createTableEntry(otf, offsets, field, fields[field]);
for (var field in fields) {
var table = fields[field];
otf.set(table, offsets.currentOffset);
offsets.currentOffset += table.length;
}
var fontData = [];
for (var i = 0; i < offsets.currentOffset; i++)
fontData.push(otf[i]);
return fontData;
},
bindWorker: function font_bindWorker(data) {
postMessage({
action: 'font',
data: {
raw: data,
fontName: this.loadedName,
mimetype: this.mimetype
}
});
},
bindDOM: function font_bindDom(data) {
var fontName = this.loadedName;
// Add the font-face rule to the document
var url = ('url(data:' + this.mimetype + ';base64,' +
window.btoa(data) + ');');
var rule = "@font-face { font-family:'" + fontName + "';src:" + url + '}';
var styleSheet = document.styleSheets[0];
styleSheet.insertRule(rule, styleSheet.cssRules.length);
return rule;
},
charsToUnicode: function fonts_chars2Unicode(chars) {
var charsCache = this.charsCache;
var str;
// if we translated this string before, just grab it from the cache
if (charsCache) {
str = charsCache[chars];
if (str)
return str;
}
// lazily create the translation cache
if (!charsCache)
charsCache = this.charsCache = Object.create(null);
// translate the string using the font's encoding
var encoding = this.encoding;
if (!encoding)
return chars;
str = '';
if (this.compositeFont) {
// composite fonts have multi-byte strings convert the string from
// single-byte to multi-byte
// XXX assuming CIDFonts are two-byte - later need to extract the
// correct byte encoding according to the PDF spec
var length = chars.length - 1; // looping over two bytes at a time so
// loop should never end on the last byte
for (var i = 0; i < length; i++) {
var charcode = int16([chars.charCodeAt(i++), chars.charCodeAt(i)]);
var unicode = encoding[charcode];
str += String.fromCharCode(unicode);
}
}
else {
for (var i = 0; i < chars.length; ++i) {
var charcode = chars.charCodeAt(i);
var unicode = encoding[charcode];
if ('undefined' == typeof(unicode)) {
// FIXME/issue 233: we're hitting this in test/pdf/sizes.pdf
// at the moment, for unknown reasons.
warn('Unencoded charcode ' + charcode);
unicode = charcode;
}
// Check if the glyph has already been converted
if (!IsNum(unicode))
unicode = encoding[unicode] = GlyphsUnicode[unicode.name];
// Handle surrogate pairs
if (unicode > 0xFFFF) {
str += String.fromCharCode(unicode & 0xFFFF);
unicode >>= 16;
}
str += String.fromCharCode(unicode);
}
}
// Enter the translated string into the cache
return charsCache[chars] = str;
}
};
return constructor;
})();
/**
* Type1Parser encapsulate the needed code for parsing a Type1 font
* program. Some of its logic depends on the Type2 charstrings
* structure.
*/
var Type1Parser = function() {
/*
* Decrypt a Sequence of Ciphertext Bytes to Produce the Original Sequence
* of Plaintext Bytes. The function took a key as a parameter which can be
* for decrypting the eexec block of for decoding charStrings.
*/
var kEexecEncryptionKey = 55665;
var kCharStringsEncryptionKey = 4330;
function decrypt(stream, key, discardNumber) {
var r = key, c1 = 52845, c2 = 22719;
var decryptedString = [];
var value = '';
var count = stream.length;
for (var i = 0; i < count; i++) {
value = stream[i];
decryptedString[i] = value ^ (r >> 8);
r = ((value + r) * c1 + c2) & ((1 << 16) - 1);
}
return decryptedString.slice(discardNumber);
};
/*
* CharStrings are encoded following the the CharString Encoding sequence
* describe in Chapter 6 of the "Adobe Type1 Font Format" specification.
* The value in a byte indicates a command, a number, or subsequent bytes
* that are to be interpreted in a special way.
*
* CharString Number Encoding:
* A CharString byte containing the values from 32 through 255 inclusive
* indicate an integer. These values are decoded in four ranges.
*
* 1. A CharString byte containing a value, v, between 32 and 246 inclusive,
* indicate the integer v - 139. Thus, the integer values from -107 through
* 107 inclusive may be encoded in single byte.
*
* 2. A CharString byte containing a value, v, between 247 and 250 inclusive,
* indicates an integer involving the next byte, w, according to the formula:
* [(v - 247) x 256] + w + 108
*
* 3. A CharString byte containing a value, v, between 251 and 254 inclusive,
* indicates an integer involving the next byte, w, according to the formula:
* -[(v - 251) * 256] - w - 108
*
* 4. A CharString containing the value 255 indicates that the next 4 bytes
* are a two complement signed integer. The first of these bytes contains the
* highest order bits, the second byte contains the next higher order bits
* and the fourth byte contain the lowest order bits.
*
*
* CharString Command Encoding:
* CharStrings commands are encoded in 1 or 2 bytes.
*
* Single byte commands are encoded in 1 byte that contains a value between
* 0 and 31 inclusive.
* If a command byte contains the value 12, then the value in the next byte
* indicates a command. This "escape" mechanism allows many extra commands
* to be encoded and this encoding technique helps to minimize the length of
* the charStrings.
*/
var charStringDictionary = {
'1': 'hstem',
'3': 'vstem',
'4': 'vmoveto',
'5': 'rlineto',
'6': 'hlineto',
'7': 'vlineto',
'8': 'rrcurveto',
// closepath is a Type1 command that do not take argument and is useless
// in Type2 and it can simply be ignored.
'9': null, // closepath
'10': 'callsubr',
// return is normally used inside sub-routines to tells to the execution
// flow that it can be back to normal.
// During the translation process Type1 charstrings will be flattened and
// sub-routines will be embedded directly into the charstring directly, so
// this can be ignored safely.
'11': 'return',
'12': {
// dotsection is a Type1 command to specify some hinting feature for dots
// that do not take a parameter and it can safely be ignored for Type2.
'0': null, // dotsection
// [vh]stem3 are Type1 only and Type2 supports [vh]stem with multiple
// parameters, so instead of returning [vh]stem3 take a shortcut and
// return [vhstem] instead.
'1': 'vstem',
'2': 'hstem',
// Type1 only command with command not (yet) built-in ,throw an error
'6': -1, // seac
'7': -1, //sbw
'11': 'sub',
'12': 'div',
// callothersubr is a mechanism to make calls on the postscript
// interpreter, this is not supported by Type2 charstring but hopefully
// most of the default commands can be ignored safely.
'16': 'callothersubr',
'17': 'pop',
// setcurrentpoint sets the current point to x, y without performing a
// moveto (this is a one shot positionning command). This is used only
// with the return of an OtherSubrs call.
// TODO Implement the OtherSubrs charstring embedding and replace this
// call by a no-op, like 2 'pop' commands for example.
'33': null //setcurrentpoint
},
'13': 'hsbw',
'14': 'endchar',
'21': 'rmoveto',
'22': 'hmoveto',
'30': 'vhcurveto',
'31': 'hvcurveto'
};
var kEscapeCommand = 12;
function decodeCharString(array) {
var charstring = [];
var lsb = 0;
var width = 0;
var used = false;
var value = '';
var count = array.length;
for (var i = 0; i < count; i++) {
value = array[i];
if (value < 32) {
var command = null;
if (value == kEscapeCommand) {
var escape = array[++i];
// TODO Clean this code
if (escape == 16) {
var index = charstring.pop();
var argc = charstring.pop();
for (var j = 0; j < argc; j++)
charstring.push('drop');
// If the flex mechanishm is not used in a font program, Adobe
// state that that entries 0, 1 and 2 can simply be replace by
// {}, which means that we can simply ignore them.
if (index < 3) {
continue;
}
// This is the same things about hint replacement, if it is not used
// entry 3 can be replaced by {3}
if (index == 3) {
charstring.push(3);
i++;
continue;
}
}
command = charStringDictionary['12'][escape];
} else {
// TODO Clean this code
if (value == 13) {
if (charstring.length == 2) {
width = charstring[1];
} else if (charstring.length == 4 && charstring[3] == 'div') {
width = charstring[1] / charstring[2];
} else {
error('Unsupported hsbw format: ' + charstring);
}
lsb = charstring[0];
charstring.push(lsb, 'hmoveto');
charstring.splice(0, 1);
continue;
}
command = charStringDictionary[value];
}
// Some charstring commands are meaningless in Type2 and will return
// a null, let's just ignored them
if (!command && i < count) {
continue;
} else if (!command) {
break;
} else if (command == -1) {
error('Support for Type1 command ' + value +
' (' + escape + ') is not implemented in charstring: ' +
charString);
}
value = command;
} else if (value <= 246) {
value = value - 139;
} else if (value <= 250) {
value = ((value - 247) * 256) + array[++i] + 108;
} else if (value <= 254) {
value = -((value - 251) * 256) - array[++i] - 108;
} else {
value = (array[++i] & 0xff) << 24 | (array[++i] & 0xff) << 16 |
(array[++i] & 0xff) << 8 | (array[++i] & 0xff) << 0;
}
charstring.push(value);
}
return { charstring: charstring, width: width, lsb: lsb };
};
/**
* Returns an object containing a Subrs array and a CharStrings
* array extracted from and eexec encrypted block of data
*/
function readNumberArray(str, index) {
var start = ++index;
var count = 0;
while (str[index++] != ']')
count++;
var array = str.substr(start, count).split(' ');
for (var i = 0; i < array.length; i++)
array[i] = parseFloat(array[i] || 0);
return array;
};
function readNumber(str, index) {
while (str[index++] == ' ');
var start = index;
var count = 0;
while (str[index++] != ' ')
count++;
return parseFloat(str.substr(start, count) || 0);
};
this.extractFontProgram = function t1_extractFontProgram(stream) {
var eexec = decrypt(stream, kEexecEncryptionKey, 4);
var eexecStr = '';
for (var i = 0; i < eexec.length; i++)
eexecStr += String.fromCharCode(eexec[i]);
var glyphsSection = false, subrsSection = false;
var program = {
subrs: [],
charstrings: [],
properties: {
'private': {}
}
};
var glyph = '';
var token = '';
var length = 0;
var c = '';
var count = eexecStr.length;
for (var i = 0; i < count; i++) {
var getToken = function() {
while(i < count && (eexecStr[i] == ' ' || eexecStr[i] == '\n'))
++i;
var t = '';
while(i < count && !(eexecStr[i] == ' ' || eexecStr[i] == '\n'))
t += eexecStr[i++];
return t;
}
var c = eexecStr[i];
if ((glyphsSection || subrsSection) && c == 'R') {
var data = eexec.slice(i + 3, i + 3 + length);
var encoded = decrypt(data, kCharStringsEncryptionKey, 4);
var str = decodeCharString(encoded);
if (glyphsSection) {
program.charstrings.push({
glyph: glyph,
data: str.charstring,
lsb: str.lsb,
width: str.width
});
} else {
program.subrs.push(str.charstring);
}
i += length + 3;
} else if (c == ' ' || c == '\n') {
length = parseInt(token);
token = '';
} else {
token += c;
if (!glyphsSection) {
switch (token) {
case '/CharString':
glyphsSection = true;
break;
case '/Subrs':
++i;
var num = parseInt(getToken());
getToken(); // read in 'array'
for (var j = 0; j < num; ++j) {
var t = getToken(); // read in 'dup'
if (t == 'ND')
break;
var index = parseInt(getToken());
if (index > j)
j = index;
var length = parseInt(getToken());
getToken(); // read in 'RD'
var data = eexec.slice(i + 1, i + 1 + length);
var encoded = decrypt(data, kCharStringsEncryptionKey, 4);
var str = decodeCharString(encoded);
i = i + 1 + length;
getToken(); //read in 'NP'
program.subrs[index] = str.charstring;
}
break;
case '/BlueValues':
case '/OtherBlues':
case '/FamilyBlues':
case '/FamilyOtherBlues':
case '/StemSnapH':
case '/StemSnapV':
program.properties.private[token.substring(1)] =
readNumberArray(eexecStr, i + 2);
break;
case '/StdHW':
case '/StdVW':
program.properties.private[token.substring(1)] =
readNumberArray(eexecStr, i + 2)[0];
break;
case '/BlueShift':
case '/BlueFuzz':
case '/BlueScale':
case '/LanguageGroup':
case '/ExpansionFactor':
program.properties.private[token.substring(1)] =
readNumber(eexecStr, i + 1);
break;
}
} else if (c == '/') {
token = glyph = '';
while ((c = eexecStr[++i]) != ' ')
glyph += c;
}
}
}
return program;
},
this.extractFontHeader = function t1_extractFontProgram(stream) {
var headerString = '';
for (var i = 0; i < stream.length; i++)
headerString += String.fromCharCode(stream[i]);
var info = {
textMatrix: null
};
var token = '';
var count = headerString.length;
for (var i = 0; i < count; i++) {
var c = headerString[i];
if (c == ' ' || c == '\n') {
switch (token) {
case '/FontMatrix':
var matrix = readNumberArray(headerString, i + 1);
// The FontMatrix is in unitPerEm, so make it pixels
for (var j = 0; j < matrix.length; j++)
matrix[j] *= 1000;
// Make the angle into the right direction
matrix[2] *= -1;
info.textMatrix = matrix;
break;
}
token = '';
} else {
token += c;
}
}
return info;
};
};
/**
* The CFF class takes a Type1 file and wrap it into a 'Compact Font Format',
* which itself embed Type2 charstrings.
*/
var CFFStrings = [
'.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
'equal', 'greater', 'question', 'at', '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', 'bracketleft', 'backslash', 'bracketright', 'asciicircum',
'underscore', 'quoteleft', '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', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase',
'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown',
'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent',
'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash',
'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae',
'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior',
'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn',
'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters',
'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior',
'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring',
'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave',
'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute',
'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute',
'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron',
'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde',
'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute',
'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex',
'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex',
'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall',
'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall',
'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', '266 ff',
'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle',
'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior',
'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior',
'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior',
'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior',
'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall',
'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior',
'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth',
'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds',
'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior',
'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior',
'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior',
'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior',
'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall',
'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall',
'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall',
'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall',
'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall',
'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003',
'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'
];
var type1Parser = new Type1Parser();
var CFF = function(name, file, properties) {
// Get the data block containing glyphs and subrs informations
var length1 = file.dict.get('Length1');
var length2 = file.dict.get('Length2');
var headerBlock = file.getBytes(length1);
var header = type1Parser.extractFontHeader(headerBlock);
for (var info in header)
properties[info] = header[info];
// Decrypt the data blocks and retrieve it's content
var eexecBlock = file.getBytes(length2);
var data = type1Parser.extractFontProgram(eexecBlock);
for (var info in data.properties)
properties[info] = data.properties[info];
var charstrings = this.getOrderedCharStrings(data.charstrings);
var type2Charstrings = this.getType2Charstrings(charstrings);
var subrs = this.getType2Subrs(data.subrs);
this.charstrings = charstrings;
this.data = this.wrap(name, type2Charstrings, this.charstrings,
subrs, properties);
};
CFF.prototype = {
createCFFIndexHeader: function cff_createCFFIndexHeader(objects, isByte) {
// First 2 bytes contains the number of objects contained into this index
var count = objects.length;
// If there is no object, just create an array saying that with another
// offset byte.
if (count == 0)
return '\x00\x00\x00';
var data = String.fromCharCode(count >> 8, count & 0xff);
// Next byte contains the offset size use to reference object in the file
// Actually we're using 0x04 to be sure to be able to store everything
// without thinking of it while coding.
data += '\x04';
// Add another offset after this one because we need a new offset
var relativeOffset = 1;
for (var i = 0; i < count + 1; i++) {
data += String.fromCharCode((relativeOffset >>> 24) & 0xFF,
(relativeOffset >> 16) & 0xFF,
(relativeOffset >> 8) & 0xFF,
relativeOffset & 0xFF);
if (objects[i])
relativeOffset += objects[i].length;
}
for (var i = 0; i < count; i++) {
for (var j = 0; j < objects[i].length; j++)
data += isByte ? String.fromCharCode(objects[i][j] & 0xFF) :
objects[i][j];
}
return data;
},
encodeNumber: function cff_encodeNumber(value) {
if (value >= -32768 && value <= 32767) {
return '\x1c' +
String.fromCharCode((value >> 8) & 0xFF) +
String.fromCharCode(value & 0xFF);
} else if (value >= (-2147483648) && value <= 2147483647) {
value ^= 0xffffffff;
value += 1;
return '\xff' +
String.fromCharCode((value >> 24) & 0xFF) +
String.fromCharCode((value >> 16) & 0xFF) +
String.fromCharCode((value >> 8) & 0xFF) +
String.fromCharCode(value & 0xFF);
}
error('Value: ' + value + ' is not allowed');
return null;
},
getOrderedCharStrings: function cff_getOrderedCharStrings(glyphs) {
var charstrings = [];
for (var i = 0; i < glyphs.length; i++) {
var glyph = glyphs[i];
var unicode = GlyphsUnicode[glyph.glyph];
if (!unicode) {
if (glyph.glyph != '.notdef') {
warn(glyph.glyph +
' does not have an entry in the glyphs unicode dictionary');
}
} else {
charstrings.push({
glyph: glyph,
unicode: unicode,
charstring: glyph.data,
width: glyph.width,
lsb: glyph.lsb
});
}
}
charstrings.sort(function charstrings_sort(a, b) {
return a.unicode - b.unicode;
});
return charstrings;
},
getType2Charstrings: function cff_getType2Charstrings(type1Charstrings) {
var type2Charstrings = [];
var count = type1Charstrings.length;
for (var i = 0; i < count; i++) {
var charstring = type1Charstrings[i].charstring;
type2Charstrings.push(this.flattenCharstring(charstring.slice(),
this.commandsMap));
}
return type2Charstrings;
},
getType2Subrs: function cff_getType2Charstrings(type1Subrs) {
var bias = 0;
var count = type1Subrs.length;
if (count < 1240)
bias = 107;
else if (count < 33900)
bias = 1131;
else
bias = 32768;
// Add a bunch of empty subrs to deal with the Type2 bias
var type2Subrs = [];
for (var i = 0; i < bias; i++)
type2Subrs.push([0x0B]);
for (var i = 0; i < count; i++) {
var subr = type1Subrs[i];
if (!subr)
subr = [0x0B];
type2Subrs.push(this.flattenCharstring(subr, this.commandsMap));
}
return type2Subrs;
},
/*
* Flatten the commands by interpreting the postscript code and replacing
* every 'callsubr', 'callothersubr' by the real commands.
*/
commandsMap: {
'hstem': 1,
'vstem': 3,
'vmoveto': 4,
'rlineto': 5,
'hlineto': 6,
'vlineto': 7,
'rrcurveto': 8,
'callsubr': 10,
'return': 11,
'sub': [12, 11],
'div': [12, 12],
'pop': [1, 12, 18],
'drop' : [12, 18],
'endchar': 14,
'rmoveto': 21,
'hmoveto': 22,
'vhcurveto': 30,
'hvcurveto': 31
},
flattenCharstring: function flattenCharstring(charstring, map) {
for (var i = 0; i < charstring.length; i++) {
var command = charstring[i];
if (command.charAt) {
var cmd = map[command];
assert(cmd, 'Unknow command: ' + command);
if (IsArray(cmd)) {
charstring.splice(i++, 1, cmd[0], cmd[1]);
} else {
charstring[i] = cmd;
}
} else {
// Type1 charstring use a division for number above 32000
if (command > 32000) {
var divisor = charstring[i + 1];
command /= divisor;
charstring.splice(i, 3, 28, command >> 8, command & 0xff);
} else {
charstring.splice(i, 1, 28, command >> 8, command & 0xff);
}
i += 2;
}
}
return charstring;
},
wrap: function wrap(name, glyphs, charstrings, subrs, properties) {
var fields = {
// major version, minor version, header size, offset size
'header': '\x01\x00\x04\x04',
'names': this.createCFFIndexHeader([name]),
'topDict': (function topDict(self) {
return function() {
var dict =
'\x00\x01\x01\x01\x30' +
'\xf8\x1b\x00' + // version
'\xf8\x1c\x01' + // Notice
'\xf8\x1d\x02' + // FullName
'\xf8\x1e\x03' + // FamilyName
'\xf8\x1f\x04' + // Weight
'\x1c\x00\x00\x10'; // Encoding
var boundingBox = properties.bbox;
for (var i = 0; i < boundingBox.length; i++)
dict += self.encodeNumber(boundingBox[i]);
dict += '\x05'; // FontBBox;
var offset = fields.header.length +
fields.names.length +
(dict.length + (4 + 4 + 7)) +
fields.strings.length +
fields.globalSubrs.length;
dict += self.encodeNumber(offset) + '\x0f'; // Charset
offset = offset + (glyphs.length * 2) + 1;
dict += self.encodeNumber(offset) + '\x11'; // Charstrings
dict += self.encodeNumber(fields.private.length);
offset = offset + fields.charstrings.length;
dict += self.encodeNumber(offset) + '\x12'; // Private
return dict;
};
})(this),
'strings': (function strings(self) {
var strings = [
'Version 0.11', // Version
'See original notice', // Notice
name, // FullName
name, // FamilyName
'Medium' // Weight
];
return self.createCFFIndexHeader(strings);
})(this),
'globalSubrs': this.createCFFIndexHeader([]),
'charset': (function charset(self) {
var charset = '\x00'; // Encoding
var count = glyphs.length;
for (var i = 0; i < count; i++) {
var index = CFFStrings.indexOf(charstrings[i].glyph.glyph);
// Some characters like asterikmath && circlecopyrt are
// missing from the original strings, for the moment let's
// map them to .notdef and see later if it cause any
// problems
if (index == -1)
index = 0;
charset += String.fromCharCode(index >> 8, index & 0xff);
}
return charset;
})(this),
'charstrings': this.createCFFIndexHeader([[0x8B, 0x0E]].concat(glyphs),
true),
'private': (function(self) {
var data =
'\x8b\x14' + // defaultWidth
'\x8b\x15'; // nominalWidth
var fieldMap = {
BlueValues: '\x06',
OtherBlues: '\x07',
FamilyBlues: '\x08',
FamilyOtherBlues: '\x09',
StemSnapH: '\x0c\x0c',
StemSnapV: '\x0c\x0d',
BlueShift: '\x0c\x0a',
BlueFuzz: '\x0c\x0b',
BlueScale: '\x0c\x09',
LanguageGroup: '\x0c\x11',
ExpansionFactor: '\x0c\x18'
};
for (var field in fieldMap) {
if (!properties.private.hasOwnProperty(field)) continue;
var value = properties.private[field];
if (IsArray(value)) {
data += self.encodeNumber(value[0]);
for (var i = 1; i < value.length; i++)
data += self.encodeNumber(value[i] - value[i - 1]);
} else {
data += self.encodeNumber(value);
}
data += fieldMap[field];
}
data += self.encodeNumber(data.length + 4) + '\x13'; // Subrs offset
return data;
})(this),
'localSubrs': this.createCFFIndexHeader(subrs, true)
};
fields.topDict = fields.topDict();
var cff = [];
for (var index in fields) {
var field = fields[index];
for (var i = 0; i < field.length; i++)
cff.push(field.charCodeAt(i));
}
return cff;
}
};
var Type2CFF = (function() {
// TODO: replace parsing code with the Type2Parser in font_utils.js
function constructor(file, properties) {
var bytes = file.getBytes();
this.bytes = bytes;
this.properties = properties;
// Other classes expect this.data to be a Javascript array
var data = [];
for (var i = 0, ii = bytes.length; i < ii; ++i)
data.push(bytes[i]);
this.data = data;
this.parse();
};
constructor.prototype = {
parse: function cff_parse() {
var header = this.parseHeader();
var nameIndex = this.parseIndex(header.endPos);
var dictIndex = this.parseIndex(nameIndex.endPos);
if (dictIndex.length != 1)
error('More than 1 font');
var stringIndex = this.parseIndex(dictIndex.endPos);
var gsubrIndex = this.parseIndex(stringIndex.endPos);
var strings = this.getStrings(stringIndex);
var baseDict = this.parseDict(dictIndex.get(0));
var topDict = this.getTopDict(baseDict, strings);
var bytes = this.bytes;
var privInfo = topDict['Private'];
var privOffset = privInfo[1], privLength = privInfo[0];
var privBytes = bytes.subarray(privOffset, privOffset + privLength);
baseDict = this.parseDict(privBytes);
var privDict = this.getPrivDict(baseDict, strings);
TODO('Parse encoding');
var charStrings = this.parseIndex(topDict['CharStrings']);
var charset = this.parseCharsets(topDict['charset'], charStrings.length,
strings);
// charstrings contains info about glyphs (one element per glyph
// containing mappings for {unicode, width})
var charstrings = this.getCharStrings(charset, charStrings,
privDict, this.properties);
// create the mapping between charstring and glyph id
var glyphIds = [];
for (var i = 0, ii = charstrings.length; i < ii; ++i) {
glyphIds.push(charstrings[i].gid);
}
this.charstrings = charstrings;
this.glyphIds = glyphIds;
},
getCharStrings: function cff_charstrings(charsets, charStrings,
privDict, properties) {
var widths = properties.widths;
var defaultWidth = privDict['defaultWidthX'];
var nominalWidth = privDict['nominalWidthX'];
var charstrings = [];
for (var i = 0, ii = charsets.length; i < ii; ++i) {
var charName = charsets[i];
var charCode = GlyphsUnicode[charName];
if (charCode) {
var width = widths[charCode] || defaultWidth;
charstrings.push({unicode: charCode, width: width, gid: i});
} else {
if (charName !== '.notdef')
warn('Cannot find unicode for glyph ' + charName);
}
}
// sort the arry by the unicode value
charstrings.sort(function(a, b) {return a.unicode - b.unicode});
return charstrings;
},
parseEncoding: function cff_parseencoding(pos) {
if (pos == 0) {
return Encodings.StandardEncoding;
} else if (pos == 1) {
return Encodings.ExpertEncoding;
}
error('not implemented encodings');
},
parseCharsets: function cff_parsecharsets(pos, length, strings) {
var bytes = this.bytes;
var format = bytes[pos++];
var charset = ['.notdef'];
// subtract 1 for the .notdef glyph
length -= 1;
switch (format) {
case 0:
for (var i = 0; i < length; ++i) {
var id = bytes[pos++];
id = (id << 8) | bytes[pos++];
charset.push(strings[id]);
}
return charset;
case 1:
while (charset.length <= length) {
var first = bytes[pos++];
first = (first << 8) | bytes[pos++];
var numLeft = bytes[pos++];
for (var i = 0; i <= numLeft; ++i)
charset.push(strings[first++]);
}
return charset;
case 2:
while (charset.length <= length) {
var first = bytes[pos++];
first = (first << 8) | bytes[pos++];
var numLeft = bytes[pos++];
numLeft = (numLeft << 8) | bytes[pos++];
for (var i = 0; i <= numLeft; ++i)
charset.push(strings[first++]);
}
return charset;
default:
error('Unknown charset format');
}
},
getPrivDict: function cff_getprivdict(baseDict, strings) {
var dict = {};
// default values
dict['defaultWidthX'] = 0;
dict['nominalWidthX'] = 0;
for (var i = 0, ii = baseDict.length; i < ii; ++i) {
var pair = baseDict[i];
var key = pair[0];
var value = pair[1];
switch (key) {
case 20:
dict['defaultWidthX'] = value[0];
case 21:
dict['nominalWidthX'] = value[0];
default:
TODO('interpret top dict key');
}
}
return dict;
},
getTopDict: function cff_gettopdict(baseDict, strings) {
var dict = {};
// default values
dict['Encoding'] = 0;
dict['charset'] = 0;
for (var i = 0, ii = baseDict.length; i < ii; ++i) {
var pair = baseDict[i];
var key = pair[0];
var value = pair[1];
switch (key) {
case 1:
dict['Notice'] = strings[value[0]];
break;
case 4:
dict['Weight'] = strings[value[0]];
break;
case 3094:
dict['BaseFontName'] = strings[value[0]];
break;
case 5:
dict['FontBBox'] = value;
break;
case 13:
dict['UniqueID'] = value[0];
break;
case 15:
dict['charset'] = value[0];
break;
case 16:
dict['Encoding'] = value[0];
break;
case 17:
dict['CharStrings'] = value[0];
break;
case 18:
dict['Private'] = value;
break;
default:
TODO('interpret top dict key');
}
}
return dict;
},
getStrings: function cff_getstrings(stringIndex) {
function bytesToString(bytesArr) {
var s = '';
for (var i = 0, ii = bytesArr.length; i < ii; ++i)
s += String.fromCharCode(bytesArr[i]);
return s;
}
var stringArray = [];
for (var i = 0, ii = CFFStrings.length; i < ii; ++i)
stringArray.push(CFFStrings[i]);
for (var i = 0, ii = stringIndex.length; i < ii; ++i)
stringArray.push(bytesToString(stringIndex.get(i)));
return stringArray;
},
parseHeader: function cff_parseHeader() {
var bytes = this.bytes;
var offset = 0;
while (bytes[offset] != 1)
++offset;
if (offset != 0) {
warning('cff data is shifted');
bytes = bytes.subarray(offset);
this.bytes = bytes;
}
return {
endPos: bytes[2],
offsetSize: bytes[3]
};
},
parseDict: function cff_parseDict(dict) {
var pos = 0;
function parseOperand() {
var value = dict[pos++];
if (value === 30) {
return parseFloatOperand(pos);
} else if (value === 28) {
value = dict[pos++];
value = (value << 8) | dict[pos++];
return value;
} else if (value === 29) {
value = dict[pos++];
value = (value << 8) | dict[pos++];
value = (value << 8) | dict[pos++];
value = (value << 8) | dict[pos++];
return value;
} else if (value <= 246) {
return value - 139;
} else if (value <= 250) {
return ((value - 247) * 256) + dict[pos++] + 108;
} else if (value <= 254) {
return -((value - 251) * 256) - dict[pos++] - 108;
} else {
error('Incorrect byte');
}
};
function parseFloatOperand() {
var str = '';
var eof = 15;
var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '.', 'E', 'E-', null, '-'];
var length = dict.length;
while (pos < length) {
var b = dict[pos++];
var b1 = b >> 4;
var b2 = b & 15;
if (b1 == eof)
break;
str += lookup[b1];
if (b2 == eof)
break;
str += lookup[b2];
}
return parseFloat(str);
};
var operands = [];
var entries = [];
var pos = 0;
var end = dict.length;
while (pos < end) {
var b = dict[pos];
if (b <= 21) {
if (b === 12) {
++pos;
var b = (b << 8) | dict[pos];
}
entries.push([b, operands]);
operands = [];
++pos;
} else {
operands.push(parseOperand());
}
}
return entries;
},
parseIndex: function cff_parseIndex(pos) {
var bytes = this.bytes;
var count = bytes[pos++] << 8 | bytes[pos++];
if (count == 0) {
var offsets = [];
var end = pos;
} else {
var offsetSize = bytes[pos++];
// add 1 for offset to determine size of last object
var startPos = pos + ((count + 1) * offsetSize) - 1;
var offsets = [];
for (var i = 0, ii = count + 1; i < ii; ++i) {
var offset = 0;
for (var j = 0; j < offsetSize; ++j) {
offset <<= 8;
offset += bytes[pos++];
}
offsets.push(startPos + offset);
}
var end = offsets[count];
}
return {
get: function index_get(index) {
if (index >= count)
return null;
var start = offsets[index];
var end = offsets[index + 1];
return bytes.subarray(start, end);
},
length: count,
endPos: end
};
}
};
return constructor;
})();
| make cmap glyph offset a symbolic constant
| fonts.js | make cmap glyph offset a symbolic constant | <ide><path>onts.js
<ide> encoding: null,
<ide>
<ide> checkAndRepair: function font_checkAndRepair(name, font, properties) {
<add> var kCmapGlyphOffset = 0xFF;
<add>
<ide> function readTableEntry(file) {
<ide> // tag
<ide> var tag = file.getBytes(4);
<ide> var encoding = properties.encoding;
<ide>
<ide> for (var i = 1; i < numGlyphs; i++) {
<del> glyphs.push({ unicode: i + 0xFF });
<add> glyphs.push({ unicode: i + kCmapGlyphOffset });
<ide> }
<ide>
<ide> if ('undefined' == typeof(encoding[0])) {
<ide> // the font is directly characters to glyphs with no encoding
<ide> // so create an identity encoding
<ide> for (i = 0; i < numGlyphs; i++)
<del> encoding[i] = i + 0xFF;
<add> encoding[i] = i + kCmapGlyphOffset;
<ide> } else {
<ide> for (var i in encoding)
<del> encoding[i] = encoding[i] + 0xFF;
<add> encoding[i] = encoding[i] + kCmapGlyphOffset;
<ide> }
<ide>
<ide> if (!cmap) { |
|
Java | apache-2.0 | 4dd7036013de670310c4968ff3ec403fff341cc4 | 0 | plutext/docx4j-export-FO | /*
* Copyright 2007-2008, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is 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.docx4j.samples;
import java.io.OutputStream;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.FopFactory;
import org.docx4j.Docx4J;
import org.docx4j.convert.out.FOSettings;
import org.docx4j.convert.out.fo.renderers.FORendererApacheFOP;
import org.docx4j.fonts.BestMatchingMapper;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFont;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.model.fields.FieldUpdater;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
/**
* Demo of PDF output.
*
* PDF output is via XSL FO.
* First XSL FO is created, then FOP
* is used to convert that to PDF.
*
* Don't worry if you get a class not
* found warning relating to batik. It
* doesn't matter.
*
* If you don't have logging configured,
* your PDF will say "TO HIDE THESE MESSAGES,
* TURN OFF debug level logging for
* org.docx4j.convert.out.pdf.viaXSLFO". The thinking is
* that you need to be able to be warned if there
* are things in your docx which the PDF output
* doesn't support...
*
* docx4j used to also support creating
* PDF via iText and via HTML. As of docx4j 2.5.0,
* only viaXSLFO is supported. The viaIText and
* viaHTML source code can be found in src/docx4j-extras directory
*
* @author jharrop
*
*/
public class ConvertOutPDFviaXSLFO extends AbstractSample {
/*
* NOT WORKING?
*
* If you are getting:
*
* "fo:layout-master-set" must be declared before "fo:page-sequence"
*
* please check:
*
* 1. the jaxb-xslfo jar is on your classpath
*
* 2. that there is no stack trace earlier in the logs
*
* 3. your JVM has adequate memory, eg
*
* -Xmx1G -XX:MaxPermSize=128m
*
*/
// Config for non-command line use
static {
inputfilepath = null; // to generate a docx (and PDF output) containing font samples
inputfilepath = System.getProperty("user.dir") + "/sample-docs/word/sample-docx.docx";
saveFO = true;
}
// For demo/debugging purposes, save the intermediate XSL FO
// Don't do this in production!
static boolean saveFO;
public static void main(String[] args)
throws Exception {
try {
getInputFilePath(args);
} catch (IllegalArgumentException e) {
}
// Font regex (optional)
// Set regex if you want to restrict to some defined subset of fonts
// Here we have to do this before calling createContent,
// since that discovers fonts
String regex = null;
// Windows:
// String
// regex=".*(calibri|camb|cour|arial|symb|times|Times|zapf).*";
//regex=".*(calibri|camb|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*";
// Mac
// String
// regex=".*(Courier New|Arial|Times New Roman|Comic Sans|Georgia|Impact|Lucida Console|Lucida Sans Unicode|Palatino Linotype|Tahoma|Trebuchet|Verdana|Symbol|Webdings|Wingdings|MS Sans Serif|MS Serif).*";
PhysicalFonts.setRegex(regex);
// Document loading (required)
WordprocessingMLPackage wordMLPackage;
if (inputfilepath==null) {
// Create a docx
System.out.println("No input path passed, creating dummy document");
wordMLPackage = WordprocessingMLPackage.createPackage();
SampleDocumentGenerator.createContent(wordMLPackage.getMainDocumentPart());
} else {
// Load .docx or Flat OPC .xml
System.out.println("Loading file from " + inputfilepath);
wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
}
// Refresh the values of DOCPROPERTY fields
FieldUpdater updater = null;
// updater = new FieldUpdater(wordMLPackage);
// updater.update(true);
// Set up font mapper (optional)
Mapper fontMapper = new IdentityPlusMapper();
// Mapper fontMapper = new BestMatchingMapper();
wordMLPackage.setFontMapper(fontMapper);
// .. example of mapping font Times New Roman which doesn't have certain Arabic glyphs
// eg Glyph "ي" (0x64a, afii57450) not available in font "TimesNewRomanPS-ItalicMT".
// eg Glyph "ج" (0x62c, afii57420) not available in font "TimesNewRomanPS-ItalicMT".
// to a font which does
PhysicalFont font
= PhysicalFonts.get("Arial Unicode MS");
// make sure this is in your regex (if any)!!!
// if (font!=null) {
// fontMapper.put("Times New Roman", font);
// fontMapper.put("Arial", font);
// }
// fontMapper.put("Libian SC Regular", PhysicalFonts.get("SimSun"));
// FO exporter setup (required)
// .. the FOSettings object
FOSettings foSettings = Docx4J.createFOSettings();
if (saveFO) {
foSettings.setFoDumpFile(new java.io.File(inputfilepath + ".fo"));
}
foSettings.setWmlPackage(wordMLPackage);
FOUserAgent foUserAgent = FORendererApacheFOP.getFOUserAgent(foSettings);
// configure foUserAgent as desired
foUserAgent.setTitle("my title");
// foUserAgent.getRendererOptions().put("pdf-a-mode", "PDF/A-1b");
// is easier than
// foSettings.setApacheFopConfiguration(apacheFopConfiguration);
// PDF/A-1a, PDF/A-2a and PDF/A-3a require accessibility to be enabled
// see further https://stackoverflow.com/a/54587413/1031689
// foUserAgent.setAccessibility(true); // suppress "missing language information" messages from FOUserAgent .processEvent
// Document format:
// The default implementation of the FORenderer that uses Apache Fop will output
// a PDF document if nothing is passed via
// foSettings.setApacheFopMime(apacheFopMime)
// apacheFopMime can be any of the output formats defined in org.apache.fop.apps.MimeConstants eg org.apache.fop.apps.MimeConstants.MIME_FOP_IF or
// FOSettings.INTERNAL_FO_MIME if you want the fo document as the result.
//foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);
// exporter writes to an OutputStream.
String outputfilepath;
if (inputfilepath==null) {
outputfilepath = System.getProperty("user.dir") + "/OUT_FontContent.pdf";
} else {
outputfilepath = inputfilepath + ".pdf";
}
OutputStream os = new java.io.FileOutputStream(outputfilepath);
// Specify whether PDF export uses XSLT or not to create the FO
// (XSLT takes longer, but is more complete).
// Don't care what type of exporter you use
Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
// Prefer the exporter, that uses a xsl transformation
// Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
// Prefer the exporter, that doesn't use a xsl transformation (= uses a visitor)
// .. faster, but not yet at feature parity
// Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);
System.out.println("Saved: " + outputfilepath);
// Clean up, so any ObfuscatedFontPart temp files can be deleted
if (wordMLPackage.getMainDocumentPart().getFontTablePart()!=null) {
wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
}
// This would also do it, via finalize() methods
updater = null;
foSettings = null;
wordMLPackage = null;
}
} | src/samples/docx4j/org/docx4j/samples/ConvertOutPDFviaXSLFO.java | /*
* Copyright 2007-2008, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is 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.docx4j.samples;
import java.io.OutputStream;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.FopFactory;
import org.docx4j.Docx4J;
import org.docx4j.convert.out.FOSettings;
import org.docx4j.convert.out.fo.renderers.FORendererApacheFOP;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFont;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.model.fields.FieldUpdater;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
/**
* Demo of PDF output.
*
* PDF output is via XSL FO.
* First XSL FO is created, then FOP
* is used to convert that to PDF.
*
* Don't worry if you get a class not
* found warning relating to batik. It
* doesn't matter.
*
* If you don't have logging configured,
* your PDF will say "TO HIDE THESE MESSAGES,
* TURN OFF debug level logging for
* org.docx4j.convert.out.pdf.viaXSLFO". The thinking is
* that you need to be able to be warned if there
* are things in your docx which the PDF output
* doesn't support...
*
* docx4j used to also support creating
* PDF via iText and via HTML. As of docx4j 2.5.0,
* only viaXSLFO is supported. The viaIText and
* viaHTML source code can be found in src/docx4j-extras directory
*
* @author jharrop
*
*/
public class ConvertOutPDFviaXSLFO extends AbstractSample {
/*
* NOT WORKING?
*
* If you are getting:
*
* "fo:layout-master-set" must be declared before "fo:page-sequence"
*
* please check:
*
* 1. the jaxb-xslfo jar is on your classpath
*
* 2. that there is no stack trace earlier in the logs
*
* 3. your JVM has adequate memory, eg
*
* -Xmx1G -XX:MaxPermSize=128m
*
*/
// Config for non-command line use
static {
inputfilepath = null; // to generate a docx (and PDF output) containing font samples
inputfilepath = System.getProperty("user.dir") + "/sample-docs/word/sample-docx.docx";
saveFO = true;
}
// For demo/debugging purposes, save the intermediate XSL FO
// Don't do this in production!
static boolean saveFO;
public static void main(String[] args)
throws Exception {
try {
getInputFilePath(args);
} catch (IllegalArgumentException e) {
}
// Font regex (optional)
// Set regex if you want to restrict to some defined subset of fonts
// Here we have to do this before calling createContent,
// since that discovers fonts
String regex = null;
// Windows:
// String
// regex=".*(calibri|camb|cour|arial|symb|times|Times|zapf).*";
//regex=".*(calibri|camb|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*";
// Mac
// String
// regex=".*(Courier New|Arial|Times New Roman|Comic Sans|Georgia|Impact|Lucida Console|Lucida Sans Unicode|Palatino Linotype|Tahoma|Trebuchet|Verdana|Symbol|Webdings|Wingdings|MS Sans Serif|MS Serif).*";
PhysicalFonts.setRegex(regex);
// Document loading (required)
WordprocessingMLPackage wordMLPackage;
if (inputfilepath==null) {
// Create a docx
System.out.println("No input path passed, creating dummy document");
wordMLPackage = WordprocessingMLPackage.createPackage();
SampleDocumentGenerator.createContent(wordMLPackage.getMainDocumentPart());
} else {
// Load .docx or Flat OPC .xml
System.out.println("Loading file from " + inputfilepath);
wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
}
// Refresh the values of DOCPROPERTY fields
FieldUpdater updater = null;
// updater = new FieldUpdater(wordMLPackage);
// updater.update(true);
// Set up font mapper (optional)
Mapper fontMapper = new IdentityPlusMapper();
wordMLPackage.setFontMapper(fontMapper);
// .. example of mapping font Times New Roman which doesn't have certain Arabic glyphs
// eg Glyph "ي" (0x64a, afii57450) not available in font "TimesNewRomanPS-ItalicMT".
// eg Glyph "ج" (0x62c, afii57420) not available in font "TimesNewRomanPS-ItalicMT".
// to a font which does
PhysicalFont font
= PhysicalFonts.get("Arial Unicode MS");
// make sure this is in your regex (if any)!!!
// if (font!=null) {
// fontMapper.put("Times New Roman", font);
// fontMapper.put("Arial", font);
// }
// fontMapper.put("Libian SC Regular", PhysicalFonts.get("SimSun"));
// FO exporter setup (required)
// .. the FOSettings object
FOSettings foSettings = Docx4J.createFOSettings();
if (saveFO) {
foSettings.setFoDumpFile(new java.io.File(inputfilepath + ".fo"));
}
foSettings.setWmlPackage(wordMLPackage);
FOUserAgent foUserAgent = FORendererApacheFOP.getFOUserAgent(foSettings);
// configure foUserAgent as desired
foUserAgent.setAccessibility(false); // suppress "missing language information" messages from FOUserAgent .processEvent
foUserAgent.setTitle("my title");
// Document format:
// The default implementation of the FORenderer that uses Apache Fop will output
// a PDF document if nothing is passed via
// foSettings.setApacheFopMime(apacheFopMime)
// apacheFopMime can be any of the output formats defined in org.apache.fop.apps.MimeConstants eg org.apache.fop.apps.MimeConstants.MIME_FOP_IF or
// FOSettings.INTERNAL_FO_MIME if you want the fo document as the result.
//foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);
// exporter writes to an OutputStream.
String outputfilepath;
if (inputfilepath==null) {
outputfilepath = System.getProperty("user.dir") + "/OUT_FontContent.pdf";
} else {
outputfilepath = inputfilepath + ".pdf";
}
OutputStream os = new java.io.FileOutputStream(outputfilepath);
// Specify whether PDF export uses XSLT or not to create the FO
// (XSLT takes longer, but is more complete).
// Don't care what type of exporter you use
Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
// Prefer the exporter, that uses a xsl transformation
// Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
// Prefer the exporter, that doesn't use a xsl transformation (= uses a visitor)
// .. faster, but not yet at feature parity
// Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);
System.out.println("Saved: " + outputfilepath);
// Clean up, so any ObfuscatedFontPart temp files can be deleted
if (wordMLPackage.getMainDocumentPart().getFontTablePart()!=null) {
wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
}
// This would also do it, via finalize() methods
updater = null;
foSettings = null;
wordMLPackage = null;
}
} | accessibility notes
| src/samples/docx4j/org/docx4j/samples/ConvertOutPDFviaXSLFO.java | accessibility notes | <ide><path>rc/samples/docx4j/org/docx4j/samples/ConvertOutPDFviaXSLFO.java
<ide> import org.docx4j.Docx4J;
<ide> import org.docx4j.convert.out.FOSettings;
<ide> import org.docx4j.convert.out.fo.renderers.FORendererApacheFOP;
<add>import org.docx4j.fonts.BestMatchingMapper;
<ide> import org.docx4j.fonts.IdentityPlusMapper;
<ide> import org.docx4j.fonts.Mapper;
<ide> import org.docx4j.fonts.PhysicalFont;
<ide>
<ide> // Set up font mapper (optional)
<ide> Mapper fontMapper = new IdentityPlusMapper();
<add>// Mapper fontMapper = new BestMatchingMapper();
<ide> wordMLPackage.setFontMapper(fontMapper);
<ide>
<ide> // .. example of mapping font Times New Roman which doesn't have certain Arabic glyphs
<ide>
<ide> FOUserAgent foUserAgent = FORendererApacheFOP.getFOUserAgent(foSettings);
<ide> // configure foUserAgent as desired
<del> foUserAgent.setAccessibility(false); // suppress "missing language information" messages from FOUserAgent .processEvent
<ide> foUserAgent.setTitle("my title");
<add>
<add>// foUserAgent.getRendererOptions().put("pdf-a-mode", "PDF/A-1b");
<add> // is easier than
<add>// foSettings.setApacheFopConfiguration(apacheFopConfiguration);
<add>
<add> // PDF/A-1a, PDF/A-2a and PDF/A-3a require accessibility to be enabled
<add> // see further https://stackoverflow.com/a/54587413/1031689
<add>// foUserAgent.setAccessibility(true); // suppress "missing language information" messages from FOUserAgent .processEvent
<add>
<ide>
<ide> // Document format:
<ide> // The default implementation of the FORenderer that uses Apache Fop will output |
|
Java | lgpl-2.1 | 25d150b203748235bb5cbb7ea102473395064f4b | 0 | rhusar/wildfly,tomazzupan/wildfly,pferraro/wildfly,rhusar/wildfly,wildfly/wildfly,99sono/wildfly,pferraro/wildfly,99sono/wildfly,golovnin/wildfly,golovnin/wildfly,wildfly/wildfly,jstourac/wildfly,xasx/wildfly,iweiss/wildfly,pferraro/wildfly,xasx/wildfly,xasx/wildfly,tadamski/wildfly,jstourac/wildfly,tomazzupan/wildfly,rhusar/wildfly,99sono/wildfly,pferraro/wildfly,tadamski/wildfly,rhusar/wildfly,iweiss/wildfly,tomazzupan/wildfly,wildfly/wildfly,iweiss/wildfly,golovnin/wildfly,jstourac/wildfly,wildfly/wildfly,jstourac/wildfly,tadamski/wildfly,iweiss/wildfly | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.ejb3.component.session;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentConfigurator;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.ComponentInterceptorFactory;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewConfigurator;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ejb3.component.EJBComponentDescription;
import org.jboss.as.ejb3.component.EJBMethodDescription;
import org.jboss.as.ejb3.component.MethodIntf;
import org.jboss.as.ejb3.deployment.EjbJarDescription;
import org.jboss.as.ejb3.tx.CMTTxInterceptor;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.ejb3.tx2.spi.TransactionalComponent;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorFactoryContext;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.logging.Logger;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import javax.ejb.AccessTimeout;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.LockType;
import javax.ejb.SessionBean;
import javax.ejb.TransactionManagementType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Jaikiran Pai
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public abstract class SessionBeanComponentDescription extends EJBComponentDescription {
private static final Logger logger = Logger.getLogger(SessionBeanComponentDescription.class);
/**
* Flag marking the presence/absence of a no-interface view on the session bean
*/
private boolean noInterfaceViewPresent;
private Map<String, MethodIntf> viewTypes = new HashMap<String, MethodIntf>();
/**
* The {@link javax.ejb.ConcurrencyManagementType} for this bean
*/
private ConcurrencyManagementType concurrencyManagementType;
/**
* The bean level {@link LockType} for this bean.
*/
private LockType beanLevelLockType;
/**
* The bean level {@link AccessTimeout} for this bean.
*/
private AccessTimeout beanLevelAccessTimeout;
/**
* The {@link LockType} applicable for a specific bean methods.
*/
private Map<EJBMethodDescription, LockType> methodLockTypes = new ConcurrentHashMap<EJBMethodDescription, LockType>();
/**
* The {@link AccessTimeout} applicable for a specific bean methods.
*/
private Map<EJBMethodDescription, AccessTimeout> methodAccessTimeouts = new ConcurrentHashMap<EJBMethodDescription, AccessTimeout>();
/**
* Methods on the component marked as @Asynchronous
*/
private final Set<MethodIdentifier> asynchronousMethods = new HashSet<MethodIdentifier>();
/**
* Views the component marked as @Asynchronous
*/
private final Set<String> asynchronousViews = new HashSet<String>();
/**
* mapped-name of the session bean
*/
private String mappedName;
public enum SessionBeanType {
STATELESS,
STATEFUL,
SINGLETON
}
/**
* Construct a new instance.
*
* @param componentName the component name
* @param componentClassName the component instance class name
* @param ejbJarDescription the module description
*/
public SessionBeanComponentDescription(final String componentName, final String componentClassName,
final EjbJarDescription ejbJarDescription, final ServiceName deploymentUnitServiceName) {
super(componentName, componentClassName, ejbJarDescription, deploymentUnitServiceName);
addDependency(SessionBeanComponent.ASYNC_EXECUTOR_SERVICE_NAME, ServiceBuilder.DependencyType.REQUIRED);
}
/**
* Returns true if this session bean component type allows concurrent access to the component instances.
* <p/>
* For example: Singleton and stateful beans allow concurrent access to the bean instances, whereas stateless beans don't.
*
* @return
*/
public abstract boolean allowsConcurrentAccess();
public void addLocalBusinessInterfaceViews(final Collection<String> classNames) {
for (final String viewClassName : classNames) {
assertNoRemoteView(viewClassName);
registerView(viewClassName, MethodIntf.LOCAL);
}
}
public void addLocalBusinessInterfaceViews(final String... classNames) {
addLocalBusinessInterfaceViews(Arrays.asList(classNames));
}
public void addNoInterfaceView() {
noInterfaceViewPresent = true;
registerView(getEJBClassName(), MethodIntf.LOCAL);
//set up interceptor for non-business methods
viewDescription.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
for (final Method method : configuration.getProxyFactory().getCachedMethods()) {
if (!Modifier.isPublic(method.getModifiers())) {
configuration.addViewInterceptor(method, new ImmediateInterceptorFactory(new NotBusinessMethodInterceptor(method)), InterceptorOrder.View.NOT_BUSINESS_METHOD);
}
}
}
});
}
public void addRemoteBusinessInterfaceViews(final Collection<String> classNames) {
for (final String viewClassName : classNames) {
assertNoLocalView(viewClassName);
registerView(viewClassName, MethodIntf.REMOTE);
}
}
private void assertNoRemoteView(final String viewClassName) {
if (viewTypes.get(viewClassName) == MethodIntf.REMOTE) {
throw new IllegalStateException("[EJB 3.1 spec, section 4.9.7] - Can't add view class: " + viewClassName
+ " as local view since it's already marked as remote view for bean: " + getEJBName());
}
}
private void assertNoLocalView(final String viewClassName) {
if (viewTypes.get(viewClassName) == MethodIntf.LOCAL) {
throw new IllegalStateException("[EJB 3.1 spec, section 4.9.7] - Can't add view class: " + viewClassName
+ " as remote view since it's already marked as local view for bean: " + getEJBName());
}
}
private void registerView(final String viewClassName, final MethodIntf viewType) {
// add it to our map
viewTypes.put(viewClassName, viewType);
// setup the ViewDescription
final ViewDescription viewDescription = new ViewDescription(this, viewClassName);
getViews().add(viewDescription);
// setup server side view interceptors
setupViewInterceptors(viewDescription);
// setup client side view interceptors
setupClientViewInterceptors(viewDescription);
}
@Override
public MethodIntf getMethodIntf(String viewClassName) {
MethodIntf methodIntf = viewTypes.get(viewClassName);
assert methodIntf != null : "no view type known for " + viewClassName;
return methodIntf;
}
public boolean hasNoInterfaceView() {
return this.noInterfaceViewPresent;
}
/**
* Sets the {@link javax.ejb.LockType} applicable for the bean.
*
* @param locktype The lock type applicable for the bean
* @throws IllegalArgumentException If the bean has already been marked for a different {@link javax.ejb.LockType} than the one passed
*/
public void setBeanLevelLockType(LockType locktype) {
if (this.beanLevelLockType != null && this.beanLevelLockType != locktype) {
throw new IllegalArgumentException(this.getEJBName() + " bean has already been marked for " + this.beanLevelLockType + " lock type. Cannot change it to " + locktype);
}
this.beanLevelLockType = locktype;
}
/**
* Returns the {@link LockType} applicable for the bean.
*
* @return
*/
public LockType getBeanLevelLockType() {
return this.beanLevelLockType;
}
/**
* Sets the {@link LockType} for the specific bean method
*
* @param lockType The applicable lock type for the method
* @param method The method
*/
public void setLockType(LockType lockType, EJBMethodDescription method) {
this.methodLockTypes.put(method, lockType);
}
public Map<EJBMethodDescription, LockType> getMethodApplicableLockTypes() {
return Collections.unmodifiableMap(this.methodLockTypes);
}
/**
* Returns the {@link AccessTimeout} applicable for the bean.
*
* @return
*/
public AccessTimeout getBeanLevelAccessTimeout() {
return this.beanLevelAccessTimeout;
}
/**
* Sets the {@link javax.ejb.AccessTimeout} applicable for the bean.
*
* @param accessTimeout The access timeout applicable for the bean
* @throws IllegalArgumentException If the bean has already been marked for a different {@link javax.ejb.AccessTimeout} than the one passed
*/
public void setBeanLevelAccessTimeout(AccessTimeout accessTimeout) {
if (this.beanLevelAccessTimeout != null && this.beanLevelAccessTimeout != accessTimeout) {
throw new IllegalArgumentException(this.getEJBName() + " bean has already been marked for " + this.beanLevelAccessTimeout + " access timeout. Cannot change it to " + accessTimeout);
}
this.beanLevelAccessTimeout = accessTimeout;
}
/**
* Sets the {@link AccessTimeout} for the specific bean method
*
* @param accessTimeout The applicable access timeout for the method
* @param method The method
*/
public void setAccessTimeout(AccessTimeout accessTimeout, EJBMethodDescription method) {
this.methodAccessTimeouts.put(method, accessTimeout);
}
public Map<EJBMethodDescription, AccessTimeout> getMethodApplicableAccessTimeouts() {
return Collections.unmodifiableMap(this.methodAccessTimeouts);
}
/**
* Returns the concurrency management type for this bean.
* <p/>
* This method returns null if the concurrency management type hasn't explicitly been set on this
* {@link SessionBeanComponentDescription}
*
* @return
*/
public ConcurrencyManagementType getConcurrencyManagementType() {
return this.concurrencyManagementType;
}
/**
* Marks the bean for bean managed concurrency.
*
* @throws IllegalStateException If the bean has already been marked for a different concurrency management type
*/
public void beanManagedConcurrency() {
if (this.concurrencyManagementType != null && this.concurrencyManagementType != ConcurrencyManagementType.BEAN) {
throw new IllegalStateException(this.getEJBName() + " bean has been marked for " + this.concurrencyManagementType + " cannot change it now!");
}
this.concurrencyManagementType = ConcurrencyManagementType.BEAN;
}
/**
* Marks this bean for container managed concurrency.
*
* @throws IllegalStateException If the bean has already been marked for a different concurrency management type
*/
public void containerManagedConcurrency() {
if (this.concurrencyManagementType != null && this.concurrencyManagementType != ConcurrencyManagementType.CONTAINER) {
throw new IllegalStateException(this.getEJBName() + " bean has been marked for " + this.concurrencyManagementType + " cannot change it now!");
}
this.concurrencyManagementType = ConcurrencyManagementType.CONTAINER;
}
/**
* Returns the mapped-name of this bean
*
* @return
*/
public String getMappedName() {
return this.mappedName;
}
/**
* Sets the mapped-name for this bean
*
* @param mappedName
*/
public void setMappedName(String mappedName) {
this.mappedName = mappedName;
}
/**
* Add an asynchronous method.
*
* @param methodIdentifier The identifier for an async method
*/
public void addAsynchronousMethod(final MethodIdentifier methodIdentifier) {
asynchronousMethods.add(methodIdentifier);
}
/**
* Set an entire view's asynchronous nature. All business methods for the view will be asynchronous.
*
* @param viewName The view name
*/
public void addAsynchronousView(final String viewName) {
asynchronousViews.add(viewName);
}
/**
* Returns the type of the session bean
*
* @return
*/
public abstract SessionBeanType getSessionBeanType();
@Override
protected void setupViewInterceptors(ViewDescription view) {
// let super do it's job first
super.setupViewInterceptors(view);
// current invocation
// tx management interceptor(s)
addTxManagementInterceptorForView(view);
}
/**
* Sets up the transaction management interceptor for all methods of the passed view.
*
* @param view The EJB bean view
*/
protected static void addTxManagementInterceptorForView(ViewDescription view) {
// add a Tx configurator
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) componentConfiguration.getComponentDescription();
// Add CMT interceptor factory
if (TransactionManagementType.CONTAINER.equals(ejbComponentDescription.getTransactionManagementType())) {
configuration.addViewInterceptor(new ComponentInterceptorFactory() {
@Override
protected Interceptor create(Component component, InterceptorFactoryContext context) {
if (!(component instanceof TransactionalComponent)) {
throw new IllegalArgumentException("Component " + component + " with component class: " + component.getComponentClass() +
" isn't a transactional component. Tx interceptors cannot be applied");
}
return new CMTTxInterceptor((TransactionalComponent) component);
}
}, InterceptorOrder.View.TRANSACTION_INTERCEPTOR);
}
}
});
}
@Override
protected void addCurrentInvocationContextFactory() {
// add the current invocation context interceptor at the beginning of the component instance post construct chain
this.getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
if (SessionBean.class.isAssignableFrom(configuration.getComponentClass())) {
configuration.addPostConstructInterceptor(SessionBeanSessionContextInjectionInterceptor.FACTORY, InterceptorOrder.ComponentPostConstruct.RESOURCE_INJECTION_INTERCEPTORS);
}
configuration.addPostConstructInterceptor(SessionInvocationContextInterceptor.FACTORY, InterceptorOrder.ComponentPostConstruct.EJB_SESSION_CONTEXT_INTERCEPTOR);
configuration.addPreDestroyInterceptor(SessionInvocationContextInterceptor.FACTORY, InterceptorOrder.ComponentPreDestroy.EJB_SESSION_CONTEXT_INTERCEPTOR);
}
});
}
@Override
protected void addCurrentInvocationContextFactory(ViewDescription view) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.addViewInterceptor(SessionInvocationContextInterceptor.FACTORY, InterceptorOrder.View.INVOCATION_CONTEXT_INTERCEPTOR);
}
});
}
@Override
public boolean isSingleton() {
return getSessionBeanType() == SessionBeanType.SINGLETON;
}
@Override
public boolean isStateful() {
return getSessionBeanType() == SessionBeanType.STATEFUL;
}
@Override
public boolean isStateless() {
return getSessionBeanType() == SessionBeanType.STATELESS;
}
}
| ejb3/src/main/java/org/jboss/as/ejb3/component/session/SessionBeanComponentDescription.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.ejb3.component.session;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentConfigurator;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.ComponentInterceptorFactory;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewConfigurator;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ejb3.component.EJBComponentDescription;
import org.jboss.as.ejb3.component.EJBMethodDescription;
import org.jboss.as.ejb3.component.MethodIntf;
import org.jboss.as.ejb3.deployment.EjbJarDescription;
import org.jboss.as.ejb3.tx.CMTTxInterceptor;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.ejb3.tx2.spi.TransactionalComponent;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorFactoryContext;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.logging.Logger;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import javax.ejb.AccessTimeout;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.LockType;
import javax.ejb.SessionBean;
import javax.ejb.TransactionManagementType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Jaikiran Pai
*/
public abstract class SessionBeanComponentDescription extends EJBComponentDescription {
private static final Logger logger = Logger.getLogger(SessionBeanComponentDescription.class);
/**
* Flag marking the presence/absence of a no-interface view on the session bean
*/
private boolean noInterfaceViewPresent;
private Map<String, MethodIntf> viewTypes = new HashMap<String, MethodIntf>();
/**
* The {@link javax.ejb.ConcurrencyManagementType} for this bean
*/
private ConcurrencyManagementType concurrencyManagementType;
/**
* The bean level {@link LockType} for this bean.
*/
private LockType beanLevelLockType;
/**
* The bean level {@link AccessTimeout} for this bean.
*/
private AccessTimeout beanLevelAccessTimeout;
/**
* The {@link LockType} applicable for a specific bean methods.
*/
private Map<EJBMethodDescription, LockType> methodLockTypes = new ConcurrentHashMap<EJBMethodDescription, LockType>();
/**
* The {@link AccessTimeout} applicable for a specific bean methods.
*/
private Map<EJBMethodDescription, AccessTimeout> methodAccessTimeouts = new ConcurrentHashMap<EJBMethodDescription, AccessTimeout>();
/**
* Methods on the component marked as @Asynchronous
*/
private final Set<MethodIdentifier> asynchronousMethods = new HashSet<MethodIdentifier>();
/**
* Views the component marked as @Asynchronous
*/
private final Set<String> asynchronousViews = new HashSet<String>();
/**
* mapped-name of the session bean
*/
private String mappedName;
public enum SessionBeanType {
STATELESS,
STATEFUL,
SINGLETON
}
/**
* Construct a new instance.
*
* @param componentName the component name
* @param componentClassName the component instance class name
* @param ejbJarDescription the module description
*/
public SessionBeanComponentDescription(final String componentName, final String componentClassName,
final EjbJarDescription ejbJarDescription, final ServiceName deploymentUnitServiceName) {
super(componentName, componentClassName, ejbJarDescription, deploymentUnitServiceName);
// Add a dependency on the asyc-executor
addDependency(SessionBeanComponent.ASYNC_EXECUTOR_SERVICE_NAME, ServiceBuilder.DependencyType.REQUIRED);
}
/**
* Returns true if this session bean component type allows concurrent access to the component instances.
* <p/>
* For example: Singleton and stateful beans allow concurrent access to the bean instances, whereas stateless beans don't.
*
* @return
*/
public abstract boolean allowsConcurrentAccess();
public void addLocalBusinessInterfaceViews(Collection<String> classNames) {
for (String viewClassName : classNames) {
// EJB 3.1 spec, section 4.9.7:
// The same business interface cannot be both a local and a remote business interface of the bean.
// if the view class is already marked as Remote, then throw an error
if (this.viewTypes.get(viewClassName) == MethodIntf.REMOTE) {
throw new IllegalStateException("[EJB 3.1 spec, section 4.9.7] - Can't add view class: " + viewClassName
+ " as local view since it's already marked as remote view for bean: " + this.getEJBName());
}
// add it to our map
viewTypes.put(viewClassName, MethodIntf.LOCAL);
// setup the ViewDescription
ViewDescription viewDescription = new ViewDescription(this, viewClassName);
this.getViews().add(viewDescription);
// setup server side view interceptors
this.setupViewInterceptors(viewDescription);
// setup client side view interceptors
this.setupClientViewInterceptors(viewDescription);
}
}
public void addLocalBusinessInterfaceViews(final String... classNames) {
addLocalBusinessInterfaceViews(Arrays.asList(classNames));
}
public void addNoInterfaceView() {
this.noInterfaceViewPresent = true;
// add it to our map
viewTypes.put(getEJBClassName(), MethodIntf.LOCAL);
// setup the ViewDescription
ViewDescription viewDescription = new ViewDescription(this, this.getEJBClassName());
this.getViews().add(viewDescription);
// setup server side view interceptors
this.setupViewInterceptors(viewDescription);
// setup client side view interceptors
this.setupClientViewInterceptors(viewDescription);
//set up interceptor for non-business methods
viewDescription.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
for (final Method method : configuration.getProxyFactory().getCachedMethods()) {
if (!Modifier.isPublic(method.getModifiers())) {
configuration.addViewInterceptor(method, new ImmediateInterceptorFactory(new NotBusinessMethodInterceptor(method)), InterceptorOrder.View.NOT_BUSINESS_METHOD);
}
}
}
});
}
public void addRemoteBusinessInterfaceViews(final Collection<String> classNames) {
for (String viewClassName : classNames) {
// EJB 3.1 spec, section 4.9.7:
// The same business interface cannot be both a local and a remote business interface of the bean.
// if the view class is already marked as Local, then throw an error
if (this.viewTypes.get(viewClassName) == MethodIntf.LOCAL) {
throw new IllegalStateException("[EJB 3.1 spec, section 4.9.7] - Can't add view class: " + viewClassName
+ " as remote view since it's already marked as local view for bean: " + this.getEJBName());
}
// add it to our map
viewTypes.put(viewClassName, MethodIntf.REMOTE);
// setup the ViewDescription
ViewDescription viewDescription = new ViewDescription(this, viewClassName);
this.getViews().add(viewDescription);
// setup server side view interceptors
this.setupViewInterceptors(viewDescription);
// setup client side view interceptors
this.setupClientViewInterceptors(viewDescription);
}
}
@Override
public MethodIntf getMethodIntf(String viewClassName) {
MethodIntf methodIntf = viewTypes.get(viewClassName);
assert methodIntf != null : "no view type known for " + viewClassName;
return methodIntf;
}
public boolean hasNoInterfaceView() {
return this.noInterfaceViewPresent;
}
/**
* Sets the {@link javax.ejb.LockType} applicable for the bean.
*
* @param locktype The lock type applicable for the bean
* @throws IllegalArgumentException If the bean has already been marked for a different {@link javax.ejb.LockType} than the one passed
*/
public void setBeanLevelLockType(LockType locktype) {
if (this.beanLevelLockType != null && this.beanLevelLockType != locktype) {
throw new IllegalArgumentException(this.getEJBName() + " bean has already been marked for " + this.beanLevelLockType + " lock type. Cannot change it to " + locktype);
}
this.beanLevelLockType = locktype;
}
/**
* Returns the {@link LockType} applicable for the bean.
*
* @return
*/
public LockType getBeanLevelLockType() {
return this.beanLevelLockType;
}
/**
* Sets the {@link LockType} for the specific bean method
*
* @param lockType The applicable lock type for the method
* @param method The method
*/
public void setLockType(LockType lockType, EJBMethodDescription method) {
this.methodLockTypes.put(method, lockType);
}
public Map<EJBMethodDescription, LockType> getMethodApplicableLockTypes() {
return Collections.unmodifiableMap(this.methodLockTypes);
}
/**
* Returns the {@link AccessTimeout} applicable for the bean.
*
* @return
*/
public AccessTimeout getBeanLevelAccessTimeout() {
return this.beanLevelAccessTimeout;
}
/**
* Sets the {@link javax.ejb.AccessTimeout} applicable for the bean.
*
* @param accessTimeout The access timeout applicable for the bean
* @throws IllegalArgumentException If the bean has already been marked for a different {@link javax.ejb.AccessTimeout} than the one passed
*/
public void setBeanLevelAccessTimeout(AccessTimeout accessTimeout) {
if (this.beanLevelAccessTimeout != null && this.beanLevelAccessTimeout != accessTimeout) {
throw new IllegalArgumentException(this.getEJBName() + " bean has already been marked for " + this.beanLevelAccessTimeout + " access timeout. Cannot change it to " + accessTimeout);
}
this.beanLevelAccessTimeout = accessTimeout;
}
/**
* Sets the {@link AccessTimeout} for the specific bean method
*
* @param accessTimeout The applicable access timeout for the method
* @param method The method
*/
public void setAccessTimeout(AccessTimeout accessTimeout, EJBMethodDescription method) {
this.methodAccessTimeouts.put(method, accessTimeout);
}
public Map<EJBMethodDescription, AccessTimeout> getMethodApplicableAccessTimeouts() {
return Collections.unmodifiableMap(this.methodAccessTimeouts);
}
/**
* Returns the concurrency management type for this bean.
* <p/>
* This method returns null if the concurrency management type hasn't explicitly been set on this
* {@link SessionBeanComponentDescription}
*
* @return
*/
public ConcurrencyManagementType getConcurrencyManagementType() {
return this.concurrencyManagementType;
}
/**
* Marks the bean for bean managed concurrency.
*
* @throws IllegalStateException If the bean has already been marked for a different concurrency management type
*/
public void beanManagedConcurrency() {
if (this.concurrencyManagementType != null && this.concurrencyManagementType != ConcurrencyManagementType.BEAN) {
throw new IllegalStateException(this.getEJBName() + " bean has been marked for " + this.concurrencyManagementType + " cannot change it now!");
}
this.concurrencyManagementType = ConcurrencyManagementType.BEAN;
}
/**
* Marks this bean for container managed concurrency.
*
* @throws IllegalStateException If the bean has already been marked for a different concurrency management type
*/
public void containerManagedConcurrency() {
if (this.concurrencyManagementType != null && this.concurrencyManagementType != ConcurrencyManagementType.CONTAINER) {
throw new IllegalStateException(this.getEJBName() + " bean has been marked for " + this.concurrencyManagementType + " cannot change it now!");
}
this.concurrencyManagementType = ConcurrencyManagementType.CONTAINER;
}
/**
* Returns the mapped-name of this bean
*
* @return
*/
public String getMappedName() {
return this.mappedName;
}
/**
* Sets the mapped-name for this bean
*
* @param mappedName
*/
public void setMappedName(String mappedName) {
this.mappedName = mappedName;
}
/**
* Add an asynchronous method.
*
* @param methodIdentifier The identifier for an async method
*/
public void addAsynchronousMethod(final MethodIdentifier methodIdentifier) {
asynchronousMethods.add(methodIdentifier);
}
/**
* Set an entire view's asynchronous nature. All business methods for the view will be asynchronous.
*
* @param viewName The view name
*/
public void addAsynchronousView(final String viewName) {
asynchronousViews.add(viewName);
}
/**
* Returns the type of the session bean
*
* @return
*/
public abstract SessionBeanType getSessionBeanType();
@Override
protected void setupViewInterceptors(ViewDescription view) {
// let super do it's job first
super.setupViewInterceptors(view);
// current invocation
// tx management interceptor(s)
addTxManagementInterceptorForView(view);
}
/**
* Sets up the transaction management interceptor for all methods of the passed view.
*
* @param view The EJB bean view
*/
protected static void addTxManagementInterceptorForView(ViewDescription view) {
// add a Tx configurator
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) componentConfiguration.getComponentDescription();
// Add CMT interceptor factory
if (TransactionManagementType.CONTAINER.equals(ejbComponentDescription.getTransactionManagementType())) {
configuration.addViewInterceptor(new ComponentInterceptorFactory() {
@Override
protected Interceptor create(Component component, InterceptorFactoryContext context) {
if (!(component instanceof TransactionalComponent)) {
throw new IllegalArgumentException("Component " + component + " with component class: " + component.getComponentClass() +
" isn't a transactional component. Tx interceptors cannot be applied");
}
return new CMTTxInterceptor((TransactionalComponent) component);
}
}, InterceptorOrder.View.TRANSACTION_INTERCEPTOR);
}
}
});
}
@Override
protected void addCurrentInvocationContextFactory() {
// add the current invocation context interceptor at the beginning of the component instance post construct chain
this.getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
if (SessionBean.class.isAssignableFrom(configuration.getComponentClass())) {
configuration.addPostConstructInterceptor(SessionBeanSessionContextInjectionInterceptor.FACTORY, InterceptorOrder.ComponentPostConstruct.RESOURCE_INJECTION_INTERCEPTORS);
}
configuration.addPostConstructInterceptor(SessionInvocationContextInterceptor.FACTORY, InterceptorOrder.ComponentPostConstruct.EJB_SESSION_CONTEXT_INTERCEPTOR);
configuration.addPreDestroyInterceptor(SessionInvocationContextInterceptor.FACTORY, InterceptorOrder.ComponentPreDestroy.EJB_SESSION_CONTEXT_INTERCEPTOR);
}
});
}
@Override
protected void addCurrentInvocationContextFactory(ViewDescription view) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.addViewInterceptor(SessionInvocationContextInterceptor.FACTORY, InterceptorOrder.View.INVOCATION_CONTEXT_INTERCEPTOR);
}
});
}
@Override
public boolean isSingleton() {
return getSessionBeanType() == SessionBeanType.SINGLETON;
}
@Override
public boolean isStateful() {
return getSessionBeanType() == SessionBeanType.STATEFUL;
}
@Override
public boolean isStateless() {
return getSessionBeanType() == SessionBeanType.STATELESS;
}
}
| refactoring SessionBeanComponentDescription - removing code duplicities
| ejb3/src/main/java/org/jboss/as/ejb3/component/session/SessionBeanComponentDescription.java | refactoring SessionBeanComponentDescription - removing code duplicities | <ide><path>jb3/src/main/java/org/jboss/as/ejb3/component/session/SessionBeanComponentDescription.java
<ide>
<ide> /**
<ide> * @author Jaikiran Pai
<add> * @author <a href="mailto:[email protected]">Richard Opalka</a>
<ide> */
<ide> public abstract class SessionBeanComponentDescription extends EJBComponentDescription {
<ide>
<ide> public SessionBeanComponentDescription(final String componentName, final String componentClassName,
<ide> final EjbJarDescription ejbJarDescription, final ServiceName deploymentUnitServiceName) {
<ide> super(componentName, componentClassName, ejbJarDescription, deploymentUnitServiceName);
<del>
<del> // Add a dependency on the asyc-executor
<ide> addDependency(SessionBeanComponent.ASYNC_EXECUTOR_SERVICE_NAME, ServiceBuilder.DependencyType.REQUIRED);
<del>
<ide> }
<ide>
<ide> /**
<ide> */
<ide> public abstract boolean allowsConcurrentAccess();
<ide>
<del> public void addLocalBusinessInterfaceViews(Collection<String> classNames) {
<del> for (String viewClassName : classNames) {
<del> // EJB 3.1 spec, section 4.9.7:
<del> // The same business interface cannot be both a local and a remote business interface of the bean.
<del>
<del> // if the view class is already marked as Remote, then throw an error
<del> if (this.viewTypes.get(viewClassName) == MethodIntf.REMOTE) {
<del> throw new IllegalStateException("[EJB 3.1 spec, section 4.9.7] - Can't add view class: " + viewClassName
<del> + " as local view since it's already marked as remote view for bean: " + this.getEJBName());
<del> }
<del> // add it to our map
<del> viewTypes.put(viewClassName, MethodIntf.LOCAL);
<del> // setup the ViewDescription
<del> ViewDescription viewDescription = new ViewDescription(this, viewClassName);
<del> this.getViews().add(viewDescription);
<del>
<del> // setup server side view interceptors
<del> this.setupViewInterceptors(viewDescription);
<del> // setup client side view interceptors
<del> this.setupClientViewInterceptors(viewDescription);
<add> public void addLocalBusinessInterfaceViews(final Collection<String> classNames) {
<add> for (final String viewClassName : classNames) {
<add> assertNoRemoteView(viewClassName);
<add> registerView(viewClassName, MethodIntf.LOCAL);
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> public void addNoInterfaceView() {
<del> this.noInterfaceViewPresent = true;
<del> // add it to our map
<del> viewTypes.put(getEJBClassName(), MethodIntf.LOCAL);
<del> // setup the ViewDescription
<del> ViewDescription viewDescription = new ViewDescription(this, this.getEJBClassName());
<del> this.getViews().add(viewDescription);
<del> // setup server side view interceptors
<del> this.setupViewInterceptors(viewDescription);
<del> // setup client side view interceptors
<del> this.setupClientViewInterceptors(viewDescription);
<del>
<add> noInterfaceViewPresent = true;
<add> registerView(getEJBClassName(), MethodIntf.LOCAL);
<ide> //set up interceptor for non-business methods
<ide> viewDescription.getConfigurators().add(new ViewConfigurator() {
<ide> @Override
<ide> }
<ide> }
<ide> });
<del>
<ide> }
<ide>
<ide> public void addRemoteBusinessInterfaceViews(final Collection<String> classNames) {
<del> for (String viewClassName : classNames) {
<del> // EJB 3.1 spec, section 4.9.7:
<del> // The same business interface cannot be both a local and a remote business interface of the bean.
<del>
<del> // if the view class is already marked as Local, then throw an error
<del> if (this.viewTypes.get(viewClassName) == MethodIntf.LOCAL) {
<del> throw new IllegalStateException("[EJB 3.1 spec, section 4.9.7] - Can't add view class: " + viewClassName
<del> + " as remote view since it's already marked as local view for bean: " + this.getEJBName());
<del> }
<del> // add it to our map
<del> viewTypes.put(viewClassName, MethodIntf.REMOTE);
<del> // setup the ViewDescription
<del> ViewDescription viewDescription = new ViewDescription(this, viewClassName);
<del> this.getViews().add(viewDescription);
<del> // setup server side view interceptors
<del> this.setupViewInterceptors(viewDescription);
<del> // setup client side view interceptors
<del> this.setupClientViewInterceptors(viewDescription);
<del> }
<add> for (final String viewClassName : classNames) {
<add> assertNoLocalView(viewClassName);
<add> registerView(viewClassName, MethodIntf.REMOTE);
<add> }
<add> }
<add>
<add> private void assertNoRemoteView(final String viewClassName) {
<add> if (viewTypes.get(viewClassName) == MethodIntf.REMOTE) {
<add> throw new IllegalStateException("[EJB 3.1 spec, section 4.9.7] - Can't add view class: " + viewClassName
<add> + " as local view since it's already marked as remote view for bean: " + getEJBName());
<add> }
<add> }
<add>
<add> private void assertNoLocalView(final String viewClassName) {
<add> if (viewTypes.get(viewClassName) == MethodIntf.LOCAL) {
<add> throw new IllegalStateException("[EJB 3.1 spec, section 4.9.7] - Can't add view class: " + viewClassName
<add> + " as remote view since it's already marked as local view for bean: " + getEJBName());
<add> }
<add> }
<add>
<add> private void registerView(final String viewClassName, final MethodIntf viewType) {
<add> // add it to our map
<add> viewTypes.put(viewClassName, viewType);
<add> // setup the ViewDescription
<add> final ViewDescription viewDescription = new ViewDescription(this, viewClassName);
<add> getViews().add(viewDescription);
<add> // setup server side view interceptors
<add> setupViewInterceptors(viewDescription);
<add> // setup client side view interceptors
<add> setupClientViewInterceptors(viewDescription);
<ide> }
<ide>
<ide> @Override |
|
Java | mit | 2cb47c5465ed746db5de3eb31094e5eba132155f | 0 | stephenc/jenkins,patbos/jenkins,oleg-nenashev/jenkins,MarkEWaite/jenkins,rsandell/jenkins,MarkEWaite/jenkins,pjanouse/jenkins,patbos/jenkins,patbos/jenkins,v1v/jenkins,MarkEWaite/jenkins,rsandell/jenkins,DanielWeber/jenkins,rsandell/jenkins,Vlatombe/jenkins,patbos/jenkins,godfath3r/jenkins,v1v/jenkins,pjanouse/jenkins,patbos/jenkins,ikedam/jenkins,MarkEWaite/jenkins,godfath3r/jenkins,patbos/jenkins,godfath3r/jenkins,pjanouse/jenkins,jenkinsci/jenkins,oleg-nenashev/jenkins,MarkEWaite/jenkins,stephenc/jenkins,daniel-beck/jenkins,recena/jenkins,v1v/jenkins,jenkinsci/jenkins,viqueen/jenkins,recena/jenkins,DanielWeber/jenkins,Vlatombe/jenkins,damianszczepanik/jenkins,viqueen/jenkins,daniel-beck/jenkins,Vlatombe/jenkins,Vlatombe/jenkins,daniel-beck/jenkins,ikedam/jenkins,recena/jenkins,oleg-nenashev/jenkins,v1v/jenkins,ikedam/jenkins,Jochen-A-Fuerbacher/jenkins,jenkinsci/jenkins,stephenc/jenkins,DanielWeber/jenkins,daniel-beck/jenkins,Jochen-A-Fuerbacher/jenkins,Vlatombe/jenkins,ikedam/jenkins,recena/jenkins,jenkinsci/jenkins,Jochen-A-Fuerbacher/jenkins,rsandell/jenkins,stephenc/jenkins,Vlatombe/jenkins,ikedam/jenkins,oleg-nenashev/jenkins,Jochen-A-Fuerbacher/jenkins,v1v/jenkins,patbos/jenkins,pjanouse/jenkins,daniel-beck/jenkins,ikedam/jenkins,daniel-beck/jenkins,godfath3r/jenkins,damianszczepanik/jenkins,oleg-nenashev/jenkins,godfath3r/jenkins,damianszczepanik/jenkins,recena/jenkins,ikedam/jenkins,pjanouse/jenkins,jenkinsci/jenkins,pjanouse/jenkins,godfath3r/jenkins,viqueen/jenkins,damianszczepanik/jenkins,MarkEWaite/jenkins,Vlatombe/jenkins,rsandell/jenkins,v1v/jenkins,damianszczepanik/jenkins,MarkEWaite/jenkins,Jochen-A-Fuerbacher/jenkins,stephenc/jenkins,DanielWeber/jenkins,recena/jenkins,stephenc/jenkins,jenkinsci/jenkins,daniel-beck/jenkins,stephenc/jenkins,recena/jenkins,viqueen/jenkins,rsandell/jenkins,DanielWeber/jenkins,DanielWeber/jenkins,jenkinsci/jenkins,daniel-beck/jenkins,damianszczepanik/jenkins,rsandell/jenkins,godfath3r/jenkins,v1v/jenkins,viqueen/jenkins,rsandell/jenkins,pjanouse/jenkins,Jochen-A-Fuerbacher/jenkins,Jochen-A-Fuerbacher/jenkins,MarkEWaite/jenkins,oleg-nenashev/jenkins,viqueen/jenkins,damianszczepanik/jenkins,ikedam/jenkins,oleg-nenashev/jenkins,DanielWeber/jenkins,jenkinsci/jenkins,viqueen/jenkins,damianszczepanik/jenkins | /*
* The MIT License
*
* Copyright (c) 2017, CloudBees, Inc.
*
* 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 hudson.security;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;
import hudson.security.captcha.CaptchaSupport;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Random;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class SecurityRealmTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
@Issue("JENKINS-43852")
public void testCacheHeaderInResponse() throws Exception {
SecurityRealm securityRealm = j.createDummySecurityRealm();
j.jenkins.setSecurityRealm(securityRealm);
WebResponse response = j.createWebClient()
.goTo("securityRealm/captcha", "")
.getWebResponse();
assertEquals(response.getContentAsString(), "");
securityRealm.setCaptchaSupport(new DummyCaptcha());
response = j.createWebClient()
.goTo("securityRealm/captcha", "image/png")
.getWebResponse();
assertThat(response.getResponseHeaderValue("Cache-Control"), is("no-cache, no-store, must-revalidate"));
assertThat(response.getResponseHeaderValue("Pragma"), is("no-cache"));
assertThat(response.getResponseHeaderValue("Expires"), is("0"));
}
private class DummyCaptcha extends CaptchaSupport {
@Override
public boolean validateCaptcha(String id, String text) {
return false;
}
@Override
public void generateImage(String id, OutputStream ios) throws IOException {
}
}
static void addSessionCookie(CookieManager manager, String domain, String path, Date date) {
manager.addCookie(new Cookie(domain, "JSESSIONID."+Integer.toHexString(new Random().nextInt()),
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
path,
date,
false));
}
@Test
public void many_sessions_logout() throws Exception {
JenkinsRule.WebClient wc = j.createWebClient();
CookieManager manager = wc.getCookieManager();
manager.setCookiesEnabled(true);
wc.goTo("login");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
byte[] array = new byte[7];
Collections.nCopies(8, 1)
.stream()
.forEach(i -> addSessionCookie(manager, "localhost", "/jenkins", tomorrow));
addSessionCookie(manager, "localhost", "/will-not-be-sent", tomorrow);
HtmlPage page = wc.goTo("logout");
StringBuilder builder = new StringBuilder();
int sessionCookies = 0;
boolean debugCookies = false;
for (Cookie cookie : manager.getCookies()) {
if (cookie.getName().startsWith("JSESSIONID")) {
++sessionCookies;
if (debugCookies) {
builder.append(cookie.getName());
String path = cookie.getPath();
if (path != null)
builder.append("; Path=").append(path);
builder.append("\n");
}
}
}
if (debugCookies) {
System.err.println(builder.toString());
}
/* There should be two surviving JSESSION* cookies:
* path:"/will-not-be-sent" -- because it wasn't sent and thus wasn't deleted.
* name:"JSESSIONID" -- because this test harness isn't winstone and the cleaning
* code is only responsible for deleting "JSESSIONID." cookies.
*
* Note: because we aren't running/testing winstone, it isn't sufficient for us to have
* this test case, we actually need an acceptance test where we're run against winstone.
*/
assertThat(sessionCookies, is(2));
}
}
| test/src/test/java/hudson/security/SecurityRealmTest.java | /*
* The MIT License
*
* Copyright (c) 2017, CloudBees, Inc.
*
* 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 hudson.security;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;
import hudson.security.captcha.CaptchaSupport;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Random;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class SecurityRealmTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
@Issue("JENKINS-43852")
public void testCacheHeaderInResponse() throws Exception {
SecurityRealm securityRealm = j.createDummySecurityRealm();
j.jenkins.setSecurityRealm(securityRealm);
WebResponse response = j.createWebClient()
.goTo("securityRealm/captcha", "")
.getWebResponse();
assertEquals(response.getContentAsString(), "");
securityRealm.setCaptchaSupport(new DummyCaptcha());
response = j.createWebClient()
.goTo("securityRealm/captcha", "image/png")
.getWebResponse();
assertThat(response.getResponseHeaderValue("Cache-Control"), is("no-cache, no-store, must-revalidate"));
assertThat(response.getResponseHeaderValue("Pragma"), is("no-cache"));
assertThat(response.getResponseHeaderValue("Expires"), is("0"));
}
private class DummyCaptcha extends CaptchaSupport {
@Override
public boolean validateCaptcha(String id, String text) {
return false;
}
@Override
public void generateImage(String id, OutputStream ios) throws IOException {
}
}
static void addSessionCookie(CookieManager manager, String domain, String path, Date date) {
manager.addCookie(new Cookie(domain, "JSESSIONID."+Integer.toHexString(new Random().nextInt()),
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
path,
date,
false));
}
@Test
public void many_sessions_logout() throws Exception {
JenkinsRule.WebClient wc = j.createWebClient();
CookieManager manager = wc.getCookieManager();
manager.setCookiesEnabled(true);
wc.goTo("login");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
byte[] array = new byte[7];
Collections.nCopies(8, 1)
.stream()
.forEach(i -> addSessionCookie(manager, "localhost", "/jenkins", tomorrow));
addSessionCookie(manager, "localhost", "/will-not-be-sent", tomorrow);
HtmlPage page = wc.goTo("logout");
StringBuilder builder = new StringBuilder();
int sessionCookies = 0;
boolean debugCookies = false;
for (Cookie cookie : manager.getCookies()) {
if (cookie.getName().startsWith("JSESSIONID")) {
++sessionCookies;
if (debugCookies) {
builder.append(cookie.getName());
String path = cookie.getPath();
if (path != null)
builder.append("; Path=").append(path);
builder.append("\n");
}
}
}
if (debugCookies) {
System.err.println(builder.toString());
}
/* There should be two surviving JSESSION* cookies:
* path:"/will-not-be-sent" -- because it wasn't sent and thus wasn't deleted.
* name:"JSESSIONID" -- because this test harness isn't winstone and the cleaning
* code is only responsible for deleting "JSESSIONID." cookies.
*
* Note: because we aren't running/testing winstone, it isn't sufficient for us to have
* this test case, we actually need an acceptance test where we're run against winstone.
*/
assertThat(sessionCookies, is(equalTo(2)));
}
}
| Remove Matchers wildcard
| test/src/test/java/hudson/security/SecurityRealmTest.java | Remove Matchers wildcard | <ide><path>est/src/test/java/hudson/security/SecurityRealmTest.java
<ide> import java.util.Collections;
<ide> import java.util.Date;
<ide> import java.util.Random;
<del>
<del>import static org.hamcrest.Matchers.*;
<ide>
<ide> import static org.hamcrest.CoreMatchers.is;
<ide> import static org.junit.Assert.assertEquals;
<ide> * Note: because we aren't running/testing winstone, it isn't sufficient for us to have
<ide> * this test case, we actually need an acceptance test where we're run against winstone.
<ide> */
<del> assertThat(sessionCookies, is(equalTo(2)));
<add> assertThat(sessionCookies, is(2));
<ide> }
<ide> } |
|
Java | apache-2.0 | 411988fd3448230a144510da5a6ea9c66c045914 | 0 | jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
package foam.nanos.http;
import foam.box.HTTPAuthorizationType;
import foam.core.X;
import foam.core.XLocator;
import foam.dao.DAO;
import foam.nanos.app.AppConfig;
import foam.nanos.auth.*;
import foam.nanos.boot.Boot;
import foam.nanos.logger.Logger;
import foam.nanos.session.Session;
import foam.util.SafetyUtil;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bouncycastle.util.encoders.Base64;
import foam.core.XFactory;
import java.io.IOException;
import static foam.mlang.MLang.AND;
import static foam.mlang.MLang.EQ;
/**
* A WebAgent decorator that adds session and authentication support.
*/
public class AuthWebAgent
extends ProxyWebAgent
{
public final static String SESSION_ID = "sessionId";
protected String permission_;
protected SendErrorHandler sendErrorHandler_;
public AuthWebAgent(String permission, WebAgent delegate, SendErrorHandler sendErrorHandler) {
setDelegate(delegate);
permission_ = permission;
sendErrorHandler_ = sendErrorHandler;
}
@Override
public void execute(X x) {
AuthService auth = (AuthService) x.get("auth");
Session session = authenticate(x);
if ( session == null ) {
try {
XLocator.set(x);
templateLogin(x);
} finally {
XLocator.set(null);
}
return;
}
if ( ! auth.check(session.getContext(), permission_) ) {
PrintWriter out = x.get(PrintWriter.class);
out.println("Access denied. Need permission: " + permission_);
((foam.nanos.logger.Logger) x.get("logger")).debug("Access denied, requires permission", permission_,"subject", x.get("subject"));
return;
}
// Create a per-request sub-context of the session context which
// contains necessary Servlet request/response objects.
X x_ = x;
X requestX = session.getContext()
.put(HttpServletRequest.class, x.get(HttpServletRequest.class))
.put(HttpServletResponse.class, x.get(HttpServletResponse.class))
.putFactory(PrintWriter.class, new XFactory() {
@Override
public Object create(X x) {
return x_.get(PrintWriter.class);
}
});
try {
XLocator.set(requestX);
super.execute(requestX);
} finally {
XLocator.set(null);
}
}
/** If provided, use user and password parameters to login and create session and cookie. **/
public Session authenticate(X x) {
Logger logger = (Logger) x.get("logger");
// context parameters
HttpServletRequest req = x.get(HttpServletRequest.class);
HttpServletResponse resp = x.get(HttpServletResponse.class);
AuthService auth = (AuthService) x.get("auth");
DAO sessionDAO = (DAO) x.get("localSessionDAO");
// query parameters
String email = req.getParameter("user");
String password = req.getParameter("password");
String actAs = req.getParameter("actAs");
String authHeader = req.getHeader("Authorization");
// instance parameters
Session session = null;
try {
if ( ! SafetyUtil.isEmpty(authHeader) ) {
StringTokenizer st = new StringTokenizer(authHeader);
if ( st.hasMoreTokens() ) {
String authType = st.nextToken();
if ( HTTPAuthorizationType.BEARER.getName().equalsIgnoreCase(authType) ) {
//
// Support for Bearer token
// wget --header="Authorization: Bearer 8b4529d8-636f-a880-d0f2-637650397a71" \
// http://localhost:8080/service/memory
//
String token = st.nextToken();
Session tmp = null;
// test and use non-clustered sessions
DAO internalSessionDAO = (DAO) x.get("localInternalSessionDAO");
if ( internalSessionDAO != null ) {
tmp = (Session) internalSessionDAO.find(token);
if ( tmp != null ) {
tmp.setClusterable(false);
}
}
if ( tmp == null ) {
tmp = (Session) sessionDAO.find(token);
}
if ( tmp != null ) {
try {
tmp.validateRemoteHost(x);
session = tmp;
String remoteIp = foam.net.IPSupport.instance().getRemoteIp(x);
if ( SafetyUtil.isEmpty(session.getRemoteHost()) ||
! SafetyUtil.equals(session.getRemoteHost(), remoteIp) ) {
session.setRemoteHost(remoteIp);
session = (Session) sessionDAO.put(session);
}
session.touch();
X effectiveContext = session.applyTo(x);
// Make context available to thread-local XLocator
XLocator.set(effectiveContext);
session.setContext(effectiveContext);
return session;
} catch( foam.core.ValidationException e ) {
logger.debug(e.getMessage(), foam.net.IPSupport.instance().getRemoteIp(x));
sendError(x, resp, HttpServletResponse.SC_UNAUTHORIZED, "Invalid Source Address.");
return null;
}
} else {
logger.debug("Invalid authentication token.", token);
sendError(x, resp, HttpServletResponse.SC_UNAUTHORIZED, "Invalid authentication token.");
return null;
}
} else if ( HTTPAuthorizationType.BASIC.getName().equalsIgnoreCase(authType) ) {
//
// Support for Basic HTTP Authentication
// Redimentary testing: curl --user username:password http://localhost:8080/service/dig
// visually inspect results, on failure you'll see the dig login page.
//
try {
String credentials = new String(Base64.decode(st.nextToken()), "UTF-8");
int index = credentials.indexOf(":");
if ( index > 0 ) {
String username = credentials.substring(0, index).trim();
if ( ! username.isEmpty() ) {
email = username;
}
String passwd = credentials.substring(index + 1).trim();
if ( ! passwd.isEmpty() ) {
password = passwd;
}
} else {
logger.debug("Invalid authentication credentials. Unable to parse username:password");
sendError(x, resp, HttpServletResponse.SC_UNAUTHORIZED, "Invalid authentication credentials.");
return null;
}
} catch (UnsupportedEncodingException e) {
logger.warning(e, "Unsupported authentication encoding, expecting Base64.");
if ( ! SafetyUtil.isEmpty(authHeader) ) {
sendError(x, resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "Supported Authentication Encodings: Base64");
return null;
}
}
} else {
logger.warning("Unsupported authorization type, expecting Basic or Bearer, received: "+authType);
if ( ! SafetyUtil.isEmpty(authHeader) ) {
sendError(x, resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "Supported Authorizations: Basic, Bearer");
return null;
}
}
}
}
try {
String sessionId = req.getParameter(SESSION_ID);
if ( SafetyUtil.isEmpty(sessionId) ) {
Cookie cookie = getCookie(req);
if ( cookie != null ) {
sessionId = cookie.getValue();
}
}
if ( ! SafetyUtil.isEmpty(sessionId) ) {
session = (Session) sessionDAO.find(sessionId);
}
if ( session == null ) {
session = createSession(x);
if ( ! SafetyUtil.isEmpty(sessionId) ) {
session.setId(sessionId);
}
session = (Session) sessionDAO.put(session);
}
session.touch();
try {
session.validateRemoteHost(x);
} catch (foam.core.ValidationException e) {
logger.debug(e.getMessage(), foam.net.IPSupport.instance().getRemoteIp(x));
if ( ! SafetyUtil.isEmpty(authHeader) ) {
sendError(x, resp, HttpServletResponse.SC_UNAUTHORIZED, "Access denied");
} else {
PrintWriter out = x.get(PrintWriter.class);
out.println("Access denied");
}
return null;
}
String remoteIp = foam.net.IPSupport.instance().getRemoteIp(x);
if ( SafetyUtil.isEmpty(session.getRemoteHost()) ||
! SafetyUtil.equals(session.getRemoteHost(), remoteIp) ) {
session.setRemoteHost(remoteIp);
session = (Session) sessionDAO.put(session);
}
User user = ((Subject) session.getContext().get("subject")).getUser();
if ( user != null &&
SafetyUtil.isEmpty(email) ) {
return session;
}
user = auth.login(session.getContext()
.put(HttpServletRequest.class, req)
.put(HttpServletResponse.class, resp), email, password);
if ( user != null ) {
if ( ! SafetyUtil.isEmpty(actAs) ) {
AgentAuthService agentService = (AgentAuthService) x.get("agentAuth");
DAO localUserDAO = (DAO) x.get("localUserDAO");
try {
User entity = (User) localUserDAO.find(Long.parseLong(actAs));
agentService.actAs(session.getContext(), entity);
} catch (java.lang.NumberFormatException e) {
logger.error("actAs must be a number:" + e);
return null;
}
}
return session;
}
// user should not be null, any login failure should throw an Exception
logger.error("AuthService.login returned null user and did not throw AuthenticationException.");
// TODO: generate stack trace.
if ( ! SafetyUtil.isEmpty(authHeader) ) {
sendError(x, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Authentication failure.");
} else {
if ( sendErrorHandler_ == null || sendErrorHandler_.redirectToLogin(x) ) {
templateLogin(x);
} else {
PrintWriter out = x.get(PrintWriter.class);
out.println("Authentication failure.");
}
}
} catch ( AuthenticationException e ) {
if ( ! SafetyUtil.isEmpty(authHeader) ) {
sendError(x, resp, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
} else {
if ( sendErrorHandler_ == null || sendErrorHandler_.redirectToLogin(x) ) {
templateLogin(x);
} else {
PrintWriter out = x.get(PrintWriter.class);
out.println("Authentication failure.");
}
}
}
} catch (java.io.IOException | IllegalStateException e) { // thrown by HttpServletResponse.sendError
logger.error(e);
}
return null;
}
private void sendError(X x, HttpServletResponse resp, int status, String message) throws java.io.IOException
{
if ( sendErrorHandler_ == null ) {
resp.sendError(status, message);
return;
}
sendErrorHandler_.sendError(x, status, message);
}
public Cookie getCookie(HttpServletRequest req) {
Cookie[] cookies = req.getCookies();
if ( cookies == null ) {
return null;
}
for ( Cookie cookie : cookies ) {
if ( SESSION_ID.equals(cookie.getName()) ) {
return cookie;
}
}
return null;
}
public Session createSession(X x) {
HttpServletRequest req = x.get(HttpServletRequest.class);
Session session = new Session((X) x.get(Boot.ROOT));
session.setRemoteHost(req.getRemoteHost());
session.setContext(session.applyTo(x));
return session;
}
public void templateLogin(X x) {
// Skip the redirect to login if it is not necessary
if ( sendErrorHandler_ != null && !sendErrorHandler_.redirectToLogin(x) ) return;
PrintWriter out = x.get(PrintWriter.class);
out.println("<form method=post>");
out.println("<h1>Login</h1>");
out.println("<br>");
out.println("<label style=\"display:inline-block;width:70px;\">Email:</label>");
out.println("<input name=\"user\" id=\"user\" type=\"string\" size=\"30\" style=\"display:inline-block;\"></input>");
out.println("<br>");
out.println("<label style=\"display:inline-block;width:70px;\">Password:</label>");
out.println("<input name=\"password\" id=\"password\" type=\"password\" size=\"30\" style=\"display:inline-block;\"></input>");
out.println("<br>");
out.println("<button id=\"login\" type=submit style=\"display:inline-block;margin-top:10px;\";>Log In</button>");
out.println("</form>");
out.println("<script>document.getElementById('login').addEventListener('click', checkEmpty); function checkEmpty() { if ( document.getElementById('user').value == '') { alert('Email Required'); } else if ( document.getElementById('password').value == '') { alert('Password Required'); } }</script>");
}
}
| src/foam/nanos/http/AuthWebAgent.java | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
package foam.nanos.http;
import foam.box.HTTPAuthorizationType;
import foam.core.X;
import foam.core.XLocator;
import foam.dao.DAO;
import foam.nanos.app.AppConfig;
import foam.nanos.auth.*;
import foam.nanos.boot.Boot;
import foam.nanos.logger.Logger;
import foam.nanos.session.Session;
import foam.util.SafetyUtil;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bouncycastle.util.encoders.Base64;
import static foam.mlang.MLang.AND;
import static foam.mlang.MLang.EQ;
/**
* A WebAgent decorator that adds session and authentication support.
*/
public class AuthWebAgent
extends ProxyWebAgent
{
public final static String SESSION_ID = "sessionId";
protected String permission_;
protected SendErrorHandler sendErrorHandler_;
public AuthWebAgent(String permission, WebAgent delegate, SendErrorHandler sendErrorHandler) {
setDelegate(delegate);
permission_ = permission;
sendErrorHandler_ = sendErrorHandler;
}
@Override
public void execute(X x) {
AuthService auth = (AuthService) x.get("auth");
Session session = authenticate(x);
if ( session == null ) {
try {
XLocator.set(x);
templateLogin(x);
} finally {
XLocator.set(null);
}
return;
}
if ( ! auth.check(session.getContext(), permission_) ) {
PrintWriter out = x.get(PrintWriter.class);
out.println("Access denied. Need permission: " + permission_);
((foam.nanos.logger.Logger) x.get("logger")).debug("Access denied, requires permission", permission_,"subject", x.get("subject"));
return;
}
// Create a per-request sub-context of the session context which
// contains necessary Servlet request/response objects.
X requestX = session.getContext()
.put(HttpServletRequest.class, x.get(HttpServletRequest.class))
.put(HttpServletResponse.class, x.get(HttpServletResponse.class))
.put(PrintWriter.class, x.get(PrintWriter.class));
try {
XLocator.set(requestX);
super.execute(requestX);
} finally {
XLocator.set(null);
}
}
/** If provided, use user and password parameters to login and create session and cookie. **/
public Session authenticate(X x) {
Logger logger = (Logger) x.get("logger");
// context parameters
HttpServletRequest req = x.get(HttpServletRequest.class);
HttpServletResponse resp = x.get(HttpServletResponse.class);
AuthService auth = (AuthService) x.get("auth");
DAO sessionDAO = (DAO) x.get("localSessionDAO");
// query parameters
String email = req.getParameter("user");
String password = req.getParameter("password");
String actAs = req.getParameter("actAs");
String authHeader = req.getHeader("Authorization");
// instance parameters
Session session = null;
try {
if ( ! SafetyUtil.isEmpty(authHeader) ) {
StringTokenizer st = new StringTokenizer(authHeader);
if ( st.hasMoreTokens() ) {
String authType = st.nextToken();
if ( HTTPAuthorizationType.BEARER.getName().equalsIgnoreCase(authType) ) {
//
// Support for Bearer token
// wget --header="Authorization: Bearer 8b4529d8-636f-a880-d0f2-637650397a71" \
// http://localhost:8080/service/memory
//
String token = st.nextToken();
Session tmp = null;
// test and use non-clustered sessions
DAO internalSessionDAO = (DAO) x.get("localInternalSessionDAO");
if ( internalSessionDAO != null ) {
tmp = (Session) internalSessionDAO.find(token);
if ( tmp != null ) {
tmp.setClusterable(false);
}
}
if ( tmp == null ) {
tmp = (Session) sessionDAO.find(token);
}
if ( tmp != null ) {
try {
tmp.validateRemoteHost(x);
session = tmp;
String remoteIp = foam.net.IPSupport.instance().getRemoteIp(x);
if ( SafetyUtil.isEmpty(session.getRemoteHost()) ||
! SafetyUtil.equals(session.getRemoteHost(), remoteIp) ) {
session.setRemoteHost(remoteIp);
session = (Session) sessionDAO.put(session);
}
session.touch();
X effectiveContext = session.applyTo(x);
// Make context available to thread-local XLocator
XLocator.set(effectiveContext);
session.setContext(effectiveContext);
return session;
} catch( foam.core.ValidationException e ) {
logger.debug(e.getMessage(), foam.net.IPSupport.instance().getRemoteIp(x));
sendError(x, resp, HttpServletResponse.SC_UNAUTHORIZED, "Invalid Source Address.");
return null;
}
} else {
logger.debug("Invalid authentication token.", token);
sendError(x, resp, HttpServletResponse.SC_UNAUTHORIZED, "Invalid authentication token.");
return null;
}
} else if ( HTTPAuthorizationType.BASIC.getName().equalsIgnoreCase(authType) ) {
//
// Support for Basic HTTP Authentication
// Redimentary testing: curl --user username:password http://localhost:8080/service/dig
// visually inspect results, on failure you'll see the dig login page.
//
try {
String credentials = new String(Base64.decode(st.nextToken()), "UTF-8");
int index = credentials.indexOf(":");
if ( index > 0 ) {
String username = credentials.substring(0, index).trim();
if ( ! username.isEmpty() ) {
email = username;
}
String passwd = credentials.substring(index + 1).trim();
if ( ! passwd.isEmpty() ) {
password = passwd;
}
} else {
logger.debug("Invalid authentication credentials. Unable to parse username:password");
sendError(x, resp, HttpServletResponse.SC_UNAUTHORIZED, "Invalid authentication credentials.");
return null;
}
} catch (UnsupportedEncodingException e) {
logger.warning(e, "Unsupported authentication encoding, expecting Base64.");
if ( ! SafetyUtil.isEmpty(authHeader) ) {
sendError(x, resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "Supported Authentication Encodings: Base64");
return null;
}
}
} else {
logger.warning("Unsupported authorization type, expecting Basic or Bearer, received: "+authType);
if ( ! SafetyUtil.isEmpty(authHeader) ) {
sendError(x, resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "Supported Authorizations: Basic, Bearer");
return null;
}
}
}
}
try {
String sessionId = req.getParameter(SESSION_ID);
if ( SafetyUtil.isEmpty(sessionId) ) {
Cookie cookie = getCookie(req);
if ( cookie != null ) {
sessionId = cookie.getValue();
}
}
if ( ! SafetyUtil.isEmpty(sessionId) ) {
session = (Session) sessionDAO.find(sessionId);
}
if ( session == null ) {
session = createSession(x);
if ( ! SafetyUtil.isEmpty(sessionId) ) {
session.setId(sessionId);
}
session = (Session) sessionDAO.put(session);
}
session.touch();
try {
session.validateRemoteHost(x);
} catch (foam.core.ValidationException e) {
logger.debug(e.getMessage(), foam.net.IPSupport.instance().getRemoteIp(x));
if ( ! SafetyUtil.isEmpty(authHeader) ) {
sendError(x, resp, HttpServletResponse.SC_UNAUTHORIZED, "Access denied");
} else {
PrintWriter out = x.get(PrintWriter.class);
out.println("Access denied");
}
return null;
}
String remoteIp = foam.net.IPSupport.instance().getRemoteIp(x);
if ( SafetyUtil.isEmpty(session.getRemoteHost()) ||
! SafetyUtil.equals(session.getRemoteHost(), remoteIp) ) {
session.setRemoteHost(remoteIp);
session = (Session) sessionDAO.put(session);
}
User user = ((Subject) session.getContext().get("subject")).getUser();
if ( user != null &&
SafetyUtil.isEmpty(email) ) {
return session;
}
user = auth.login(session.getContext()
.put(HttpServletRequest.class, req)
.put(HttpServletResponse.class, resp), email, password);
if ( user != null ) {
if ( ! SafetyUtil.isEmpty(actAs) ) {
AgentAuthService agentService = (AgentAuthService) x.get("agentAuth");
DAO localUserDAO = (DAO) x.get("localUserDAO");
try {
User entity = (User) localUserDAO.find(Long.parseLong(actAs));
agentService.actAs(session.getContext(), entity);
} catch (java.lang.NumberFormatException e) {
logger.error("actAs must be a number:" + e);
return null;
}
}
return session;
}
// user should not be null, any login failure should throw an Exception
logger.error("AuthService.login returned null user and did not throw AuthenticationException.");
// TODO: generate stack trace.
if ( ! SafetyUtil.isEmpty(authHeader) ) {
sendError(x, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Authentication failure.");
} else {
if ( sendErrorHandler_ == null || sendErrorHandler_.redirectToLogin(x) ) {
templateLogin(x);
} else {
PrintWriter out = x.get(PrintWriter.class);
out.println("Authentication failure.");
}
}
} catch ( AuthenticationException e ) {
if ( ! SafetyUtil.isEmpty(authHeader) ) {
sendError(x, resp, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
} else {
if ( sendErrorHandler_ == null || sendErrorHandler_.redirectToLogin(x) ) {
templateLogin(x);
} else {
PrintWriter out = x.get(PrintWriter.class);
out.println("Authentication failure.");
}
}
}
} catch (java.io.IOException | IllegalStateException e) { // thrown by HttpServletResponse.sendError
logger.error(e);
}
return null;
}
private void sendError(X x, HttpServletResponse resp, int status, String message) throws java.io.IOException
{
if ( sendErrorHandler_ == null ) {
resp.sendError(status, message);
return;
}
sendErrorHandler_.sendError(x, status, message);
}
public Cookie getCookie(HttpServletRequest req) {
Cookie[] cookies = req.getCookies();
if ( cookies == null ) {
return null;
}
for ( Cookie cookie : cookies ) {
if ( SESSION_ID.equals(cookie.getName()) ) {
return cookie;
}
}
return null;
}
public Session createSession(X x) {
HttpServletRequest req = x.get(HttpServletRequest.class);
Session session = new Session((X) x.get(Boot.ROOT));
session.setRemoteHost(req.getRemoteHost());
session.setContext(session.applyTo(x));
return session;
}
public void templateLogin(X x) {
// Skip the redirect to login if it is not necessary
if ( sendErrorHandler_ != null && !sendErrorHandler_.redirectToLogin(x) ) return;
PrintWriter out = x.get(PrintWriter.class);
out.println("<form method=post>");
out.println("<h1>Login</h1>");
out.println("<br>");
out.println("<label style=\"display:inline-block;width:70px;\">Email:</label>");
out.println("<input name=\"user\" id=\"user\" type=\"string\" size=\"30\" style=\"display:inline-block;\"></input>");
out.println("<br>");
out.println("<label style=\"display:inline-block;width:70px;\">Password:</label>");
out.println("<input name=\"password\" id=\"password\" type=\"password\" size=\"30\" style=\"display:inline-block;\"></input>");
out.println("<br>");
out.println("<button id=\"login\" type=submit style=\"display:inline-block;margin-top:10px;\";>Log In</button>");
out.println("</form>");
out.println("<script>document.getElementById('login').addEventListener('click', checkEmpty); function checkEmpty() { if ( document.getElementById('user').value == '') { alert('Email Required'); } else if ( document.getElementById('password').value == '') { alert('Password Required'); } }</script>");
}
}
| fix download document bugs (#4902)
| src/foam/nanos/http/AuthWebAgent.java | fix download document bugs (#4902) | <ide><path>rc/foam/nanos/http/AuthWebAgent.java
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import javax.servlet.http.HttpServletResponse;
<ide> import org.bouncycastle.util.encoders.Base64;
<add>import foam.core.XFactory;
<add>import java.io.IOException;
<ide> import static foam.mlang.MLang.AND;
<ide> import static foam.mlang.MLang.EQ;
<ide>
<ide>
<ide> // Create a per-request sub-context of the session context which
<ide> // contains necessary Servlet request/response objects.
<add> X x_ = x;
<ide> X requestX = session.getContext()
<ide> .put(HttpServletRequest.class, x.get(HttpServletRequest.class))
<ide> .put(HttpServletResponse.class, x.get(HttpServletResponse.class))
<del> .put(PrintWriter.class, x.get(PrintWriter.class));
<add> .putFactory(PrintWriter.class, new XFactory() {
<add> @Override
<add> public Object create(X x) {
<add> return x_.get(PrintWriter.class);
<add> }
<add> });
<ide>
<ide> try {
<ide> XLocator.set(requestX); |
|
JavaScript | mit | a5e7fc0a999660f98ba04d9c415a4c1249848af7 | 0 | ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt | 'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError, ArgumentsRequired, AuthenticationError, InsufficientFunds, PermissionDenied, BadRequest, BadSymbol, RateLimitExceeded, InvalidOrder } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class bigone extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bigone',
'name': 'BigONE',
'countries': [ 'CN' ],
'version': 'v3',
'rateLimit': 1200, // 500 request per 10 minutes
'has': {
'CORS': undefined,
'spot': true,
'margin': undefined, // has but unimplemented
'swap': undefined, // has but unimplemented
'future': undefined, // has but unimplemented
'option': undefined,
'cancelAllOrders': true,
'cancelOrder': true,
'createOrder': true,
'fetchBalance': true,
'fetchClosedOrders': true,
'fetchDepositAddress': true,
'fetchDeposits': true,
'fetchMarkets': true,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTime': true,
'fetchTrades': true,
'fetchTradingFee': false,
'fetchTradingFees': false,
'fetchWithdrawals': true,
'transfer': true,
'withdraw': true,
},
'timeframes': {
'1m': 'min1',
'5m': 'min5',
'15m': 'min15',
'30m': 'min30',
'1h': 'hour1',
'3h': 'hour3',
'4h': 'hour4',
'6h': 'hour6',
'12h': 'hour12',
'1d': 'day1',
'1w': 'week1',
'1M': 'month1',
},
'hostname': 'big.one', // or 'bigone.com'
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/69354403-1d532180-0c91-11ea-88ed-44c06cefdf87.jpg',
'api': {
'public': 'https://{hostname}/api/v3',
'private': 'https://{hostname}/api/v3/viewer',
},
'www': 'https://big.one',
'doc': 'https://open.big.one/docs/api.html',
'fees': 'https://bigone.zendesk.com/hc/en-us/articles/115001933374-BigONE-Fee-Policy',
'referral': 'https://b1.run/users/new?code=D3LLBVFT',
},
'api': {
'public': {
'get': [
'ping',
'asset_pairs',
'asset_pairs/{asset_pair_name}/depth',
'asset_pairs/{asset_pair_name}/trades',
'asset_pairs/{asset_pair_name}/ticker',
'asset_pairs/{asset_pair_name}/candles',
'asset_pairs/tickers',
],
},
'private': {
'get': [
'accounts',
'fund/accounts',
'assets/{asset_symbol}/address',
'orders',
'orders/{id}',
'orders/multi',
'trades',
'withdrawals',
'deposits',
],
'post': [
'orders',
'orders/{id}/cancel',
'orders/cancel',
'withdrawals',
'transfer',
],
},
},
'fees': {
'trading': {
'maker': this.parseNumber ('0.001'),
'taker': this.parseNumber ('0.001'),
},
'funding': {
'withdraw': {},
},
},
'options': {
'accountsByType': {
'spot': 'SPOT',
'funding': 'FUND',
'future': 'CONTRACT',
'swap': 'CONTRACT',
},
'transfer': {
'fillResponseFromRequest': true,
},
},
'exceptions': {
'exact': {
'10001': BadRequest, // syntax error
'10005': ExchangeError, // internal error
"Amount's scale must greater than AssetPair's base scale": InvalidOrder,
"Price mulit with amount should larger than AssetPair's min_quote_value": InvalidOrder,
'10007': BadRequest, // parameter error, {"code":10007,"message":"Amount's scale must greater than AssetPair's base scale"}
'10011': ExchangeError, // system error
'10013': BadSymbol, // {"code":10013,"message":"Resource not found"}
'10014': InsufficientFunds, // {"code":10014,"message":"Insufficient funds"}
'10403': PermissionDenied, // permission denied
'10429': RateLimitExceeded, // too many requests
'40004': AuthenticationError, // {"code":40004,"message":"invalid jwt"}
'40103': AuthenticationError, // invalid otp code
'40104': AuthenticationError, // invalid asset pin code
'40301': PermissionDenied, // {"code":40301,"message":"Permission denied withdrawal create"}
'40302': ExchangeError, // already requested
'40601': ExchangeError, // resource is locked
'40602': ExchangeError, // resource is depleted
'40603': InsufficientFunds, // insufficient resource
'40605': InvalidOrder, // {"code":40605,"message":"Price less than the minimum order price"}
'40120': InvalidOrder, // Order is in trading
'40121': InvalidOrder, // Order is already cancelled or filled
'60100': BadSymbol, // {"code":60100,"message":"Asset pair is suspended"}
},
'broad': {
},
},
'commonCurrencies': {
'CRE': 'Cybereits',
'FXT': 'FXTTOKEN',
'FREE': 'FreeRossDAO',
'MBN': 'Mobilian Coin',
'ONE': 'BigONE Token',
},
});
}
async fetchMarkets (params = {}) {
const response = await this.publicGetAssetPairs (params);
//
// {
// "code":0,
// "data":[
// {
// "id":"01e48809-b42f-4a38-96b1-c4c547365db1",
// "name":"PCX-BTC",
// "quote_scale":7,
// "quote_asset":{
// "id":"0df9c3c3-255a-46d7-ab82-dedae169fba9",
// "symbol":"BTC",
// "name":"Bitcoin",
// },
// "base_asset":{
// "id":"405484f7-4b03-4378-a9c1-2bd718ecab51",
// "symbol":"PCX",
// "name":"ChainX",
// },
// "base_scale":3,
// "min_quote_value":"0.0001",
// "max_quote_value":"35"
// },
// ]
// }
//
const markets = this.safeValue (response, 'data', []);
const result = [];
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const id = this.safeString (market, 'name');
const uuid = this.safeString (market, 'id');
const baseAsset = this.safeValue (market, 'base_asset', {});
const quoteAsset = this.safeValue (market, 'quote_asset', {});
const baseId = this.safeString (baseAsset, 'symbol');
const quoteId = this.safeString (quoteAsset, 'symbol');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const entry = {
'id': id,
'uuid': uuid,
'symbol': base + '/' + quote,
'base': base,
'quote': quote,
'settle': undefined,
'baseId': baseId,
'quoteId': quoteId,
'settleId': undefined,
'type': 'spot',
'spot': true,
'margin': false,
'swap': false,
'future': false,
'option': false,
'active': true,
'contract': false,
'linear': undefined,
'inverse': undefined,
'contractSize': undefined,
'expiry': undefined,
'expiryDatetime': undefined,
'strike': undefined,
'optionType': undefined,
'precision': {
'amount': this.safeInteger (market, 'base_scale'),
'price': this.safeInteger (market, 'quote_scale'),
},
'limits': {
'leverage': {
'min': undefined,
'max': undefined,
},
'amount': {
'min': undefined,
'max': undefined,
},
'price': {
'min': undefined,
'max': undefined,
},
'cost': {
'min': this.safeNumber (market, 'min_quote_value'),
'max': this.safeNumber (market, 'max_quote_value'),
},
},
'info': market,
};
result.push (entry);
}
return result;
}
async loadMarkets (reload = false, params = {}) {
const markets = await super.loadMarkets (reload, params);
let marketsByUuid = this.safeValue (this.options, 'marketsByUuid');
if ((marketsByUuid === undefined) || reload) {
marketsByUuid = {};
for (let i = 0; i < this.symbols.length; i++) {
const symbol = this.symbols[i];
const market = this.markets[symbol];
const uuid = this.safeString (market, 'uuid');
marketsByUuid[uuid] = market;
}
this.options['marketsByUuid'] = marketsByUuid;
}
return markets;
}
parseTicker (ticker, market = undefined) {
//
// {
// "asset_pair_name":"ETH-BTC",
// "bid":{"price":"0.021593","order_count":1,"quantity":"0.20936"},
// "ask":{"price":"0.021613","order_count":1,"quantity":"2.87064"},
// "open":"0.021795",
// "high":"0.021795",
// "low":"0.021471",
// "close":"0.021613",
// "volume":"117078.90431",
// "daily_change":"-0.000182"
// }
//
const marketId = this.safeString (ticker, 'asset_pair_name');
const symbol = this.safeSymbol (marketId, market, '-');
const timestamp = undefined;
const close = this.safeString (ticker, 'close');
const bid = this.safeValue (ticker, 'bid', {});
const ask = this.safeValue (ticker, 'ask', {});
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeString (ticker, 'high'),
'low': this.safeString (ticker, 'low'),
'bid': this.safeString (bid, 'price'),
'bidVolume': this.safeString (bid, 'quantity'),
'ask': this.safeString (ask, 'price'),
'askVolume': this.safeString (ask, 'quantity'),
'vwap': undefined,
'open': this.safeString (ticker, 'open'),
'close': close,
'last': close,
'previousClose': undefined,
'change': this.safeString (ticker, 'daily_change'),
'percentage': undefined,
'average': undefined,
'baseVolume': this.safeString (ticker, 'volume'),
'quoteVolume': undefined,
'info': ticker,
}, market, false);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'asset_pair_name': market['id'],
};
const response = await this.publicGetAssetPairsAssetPairNameTicker (this.extend (request, params));
//
// {
// "code":0,
// "data":{
// "asset_pair_name":"ETH-BTC",
// "bid":{"price":"0.021593","order_count":1,"quantity":"0.20936"},
// "ask":{"price":"0.021613","order_count":1,"quantity":"2.87064"},
// "open":"0.021795",
// "high":"0.021795",
// "low":"0.021471",
// "close":"0.021613",
// "volume":"117078.90431",
// "daily_change":"-0.000182"
// }
// }
//
const ticker = this.safeValue (response, 'data', {});
return this.parseTicker (ticker, market);
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (symbols !== undefined) {
const ids = this.marketIds (symbols);
request['pair_names'] = ids.join (',');
}
const response = await this.publicGetAssetPairsTickers (this.extend (request, params));
//
// {
// "code":0,
// "data":[
// {
// "asset_pair_name":"PCX-BTC",
// "bid":{"price":"0.000234","order_count":1,"quantity":"0.518"},
// "ask":{"price":"0.0002348","order_count":1,"quantity":"2.348"},
// "open":"0.0002343",
// "high":"0.0002348",
// "low":"0.0002162",
// "close":"0.0002348",
// "volume":"12887.016",
// "daily_change":"0.0000005"
// },
// {
// "asset_pair_name":"GXC-USDT",
// "bid":{"price":"0.5054","order_count":1,"quantity":"40.53"},
// "ask":{"price":"0.5055","order_count":1,"quantity":"38.53"},
// "open":"0.5262",
// "high":"0.5323",
// "low":"0.5055",
// "close":"0.5055",
// "volume":"603963.05",
// "daily_change":"-0.0207"
// }
// ]
// }
//
const tickers = this.safeValue (response, 'data', []);
const result = {};
for (let i = 0; i < tickers.length; i++) {
const ticker = this.parseTicker (tickers[i]);
const symbol = ticker['symbol'];
result[symbol] = ticker;
}
return this.filterByArray (result, 'symbol', symbols);
}
async fetchTime (params = {}) {
const response = await this.publicGetPing (params);
//
// {
// "data": {
// "timestamp": 1527665262168391000
// }
// }
//
const data = this.safeValue (response, 'data', {});
const timestamp = this.safeInteger (data, 'timestamp');
return parseInt (timestamp / 1000000);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'asset_pair_name': market['id'],
};
if (limit !== undefined) {
request['limit'] = limit; // default 50, max 200
}
const response = await this.publicGetAssetPairsAssetPairNameDepth (this.extend (request, params));
//
// {
// "code":0,
// "data": {
// "asset_pair_name": "EOS-BTC",
// "bids": [
// { "price": "42", "order_count": 4, "quantity": "23.33363711" }
// ],
// "asks": [
// { "price": "45", "order_count": 2, "quantity": "4193.3283464" }
// ]
// }
// }
//
const orderbook = this.safeValue (response, 'data', {});
return this.parseOrderBook (orderbook, symbol, undefined, 'bids', 'asks', 'price', 'quantity');
}
parseTrade (trade, market = undefined) {
//
// fetchTrades (public)
//
// {
// "id": 38199941,
// "price": "3378.67",
// "amount": "0.019812",
// "taker_side": "ASK",
// "created_at": "2019-01-29T06:05:56Z"
// }
//
// fetchMyTrades (private)
//
// {
// "id": 10854280,
// "asset_pair_name": "XIN-USDT",
// "price": "70",
// "amount": "1",
// "taker_side": "ASK",
// "maker_order_id": 58284908,
// "taker_order_id": 58284909,
// "maker_fee": "0.0008",
// "taker_fee": "0.07",
// "side": "SELF_TRADING",
// "inserted_at": "2019-04-16T12:00:01Z"
// },
//
// {
// "id": 10854263,
// "asset_pair_name": "XIN-USDT",
// "price": "75.7",
// "amount": "12.743149",
// "taker_side": "BID",
// "maker_order_id": null,
// "taker_order_id": 58284888,
// "maker_fee": null,
// "taker_fee": "0.0025486298",
// "side": "BID",
// "inserted_at": "2019-04-15T06:20:57Z"
// }
//
const timestamp = this.parse8601 (this.safeString2 (trade, 'created_at', 'inserted_at'));
const priceString = this.safeString (trade, 'price');
const amountString = this.safeString (trade, 'amount');
const marketId = this.safeString (trade, 'asset_pair_name');
market = this.safeMarket (marketId, market, '-');
let side = this.safeString (trade, 'side');
const takerSide = this.safeString (trade, 'taker_side');
let takerOrMaker = undefined;
if ((takerSide !== undefined) && (side !== undefined) && (side !== 'SELF_TRADING')) {
takerOrMaker = (takerSide === side) ? 'taker' : 'maker';
}
if (side === undefined) {
// taker side is not related to buy/sell side
// the following code is probably a mistake
side = (takerSide === 'ASK') ? 'sell' : 'buy';
} else {
if (side === 'BID') {
side = 'buy';
} else if (side === 'ASK') {
side = 'sell';
}
}
const makerOrderId = this.safeString (trade, 'maker_order_id');
const takerOrderId = this.safeString (trade, 'taker_order_id');
let orderId = undefined;
if (makerOrderId !== undefined) {
if (takerOrderId !== undefined) {
orderId = [ makerOrderId, takerOrderId ];
} else {
orderId = makerOrderId;
}
} else if (takerOrderId !== undefined) {
orderId = takerOrderId;
}
const id = this.safeString (trade, 'id');
const result = {
'id': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': market['symbol'],
'order': orderId,
'type': 'limit',
'side': side,
'takerOrMaker': takerOrMaker,
'price': priceString,
'amount': amountString,
'cost': undefined,
'info': trade,
};
let makerCurrencyCode = undefined;
let takerCurrencyCode = undefined;
if (takerOrMaker !== undefined) {
if (side === 'buy') {
if (takerOrMaker === 'maker') {
makerCurrencyCode = market['base'];
takerCurrencyCode = market['quote'];
} else {
makerCurrencyCode = market['quote'];
takerCurrencyCode = market['base'];
}
} else {
if (takerOrMaker === 'maker') {
makerCurrencyCode = market['quote'];
takerCurrencyCode = market['base'];
} else {
makerCurrencyCode = market['base'];
takerCurrencyCode = market['quote'];
}
}
} else if (side === 'SELF_TRADING') {
if (takerSide === 'BID') {
makerCurrencyCode = market['quote'];
takerCurrencyCode = market['base'];
} else if (takerSide === 'ASK') {
makerCurrencyCode = market['base'];
takerCurrencyCode = market['quote'];
}
}
const makerFeeCost = this.safeString (trade, 'maker_fee');
const takerFeeCost = this.safeString (trade, 'taker_fee');
if (makerFeeCost !== undefined) {
if (takerFeeCost !== undefined) {
result['fees'] = [
{ 'cost': makerFeeCost, 'currency': makerCurrencyCode },
{ 'cost': takerFeeCost, 'currency': takerCurrencyCode },
];
} else {
result['fee'] = { 'cost': makerFeeCost, 'currency': makerCurrencyCode };
}
} else if (takerFeeCost !== undefined) {
result['fee'] = { 'cost': takerFeeCost, 'currency': takerCurrencyCode };
} else {
result['fee'] = undefined;
}
return this.safeTrade (result, market);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'asset_pair_name': market['id'],
};
const response = await this.publicGetAssetPairsAssetPairNameTrades (this.extend (request, params));
//
// {
// "code": 0,
// "data": [
// {
// "id": 38199941,
// "price": "3378.67",
// "amount": "0.019812",
// "taker_side": "ASK",
// "created_at": "2019-01-29T06:05:56Z"
// },
// {
// "id": 38199934,
// "price": "3376.14",
// "amount": "0.019384",
// "taker_side": "ASK",
// "created_at": "2019-01-29T06:05:40Z"
// }
// ]
// }
//
const trades = this.safeValue (response, 'data', []);
return this.parseTrades (trades, market, since, limit);
}
parseOHLCV (ohlcv, market = undefined) {
//
// {
// close: '0.021562',
// high: '0.021563',
// low: '0.02156',
// open: '0.021563',
// time: '2019-11-21T07:54:00Z',
// volume: '59.84376'
// }
//
return [
this.parse8601 (this.safeString (ohlcv, 'time')),
this.safeNumber (ohlcv, 'open'),
this.safeNumber (ohlcv, 'high'),
this.safeNumber (ohlcv, 'low'),
this.safeNumber (ohlcv, 'close'),
this.safeNumber (ohlcv, 'volume'),
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (limit === undefined) {
limit = 100; // default 100, max 500
}
const request = {
'asset_pair_name': market['id'],
'period': this.timeframes[timeframe],
'limit': limit,
};
if (since !== undefined) {
// const start = parseInt (since / 1000);
const duration = this.parseTimeframe (timeframe);
const end = this.sum (since, limit * duration * 1000);
request['time'] = this.iso8601 (end);
}
const response = await this.publicGetAssetPairsAssetPairNameCandles (this.extend (request, params));
//
// {
// code: 0,
// data: [
// {
// close: '0.021656',
// high: '0.021658',
// low: '0.021652',
// open: '0.021652',
// time: '2019-11-21T09:30:00Z',
// volume: '53.08664'
// },
// {
// close: '0.021652',
// high: '0.021656',
// low: '0.021652',
// open: '0.021656',
// time: '2019-11-21T09:29:00Z',
// volume: '88.39861'
// },
// ]
// }
//
const data = this.safeValue (response, 'data', []);
return this.parseOHLCVs (data, market, timeframe, since, limit);
}
parseBalance (response) {
const result = {
'info': response,
'timestamp': undefined,
'datetime': undefined,
};
const balances = this.safeValue (response, 'data', []);
for (let i = 0; i < balances.length; i++) {
const balance = balances[i];
const symbol = this.safeString (balance, 'asset_symbol');
const code = this.safeCurrencyCode (symbol);
const account = this.account ();
account['total'] = this.safeString (balance, 'balance');
account['used'] = this.safeString (balance, 'locked_balance');
result[code] = account;
}
return this.safeBalance (result);
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
const type = this.safeString (params, 'type', '');
params = this.omit (params, 'type');
const method = 'privateGet' + this.capitalize (type) + 'Accounts';
const response = await this[method] (params);
//
// {
// "code":0,
// "data":[
// {"asset_symbol":"NKC","balance":"0","locked_balance":"0"},
// {"asset_symbol":"UBTC","balance":"0","locked_balance":"0"},
// {"asset_symbol":"READ","balance":"0","locked_balance":"0"},
// ],
// }
//
return this.parseBalance (response);
}
parseOrder (order, market = undefined) {
//
// {
// "id": 10,
// "asset_pair_name": "EOS-BTC",
// "price": "10.00",
// "amount": "10.00",
// "filled_amount": "9.0",
// "avg_deal_price": "12.0",
// "side": "ASK",
// "state": "FILLED",
// "created_at":"2019-01-29T06:05:56Z",
// "updated_at":"2019-01-29T06:05:56Z",
// }
//
const id = this.safeString (order, 'id');
const marketId = this.safeString (order, 'asset_pair_name');
const symbol = this.safeSymbol (marketId, market, '-');
const timestamp = this.parse8601 (this.safeString (order, 'created_at'));
const price = this.safeString (order, 'price');
const amount = this.safeString (order, 'amount');
const average = this.safeString (order, 'avg_deal_price');
const filled = this.safeString (order, 'filled_amount');
const status = this.parseOrderStatus (this.safeString (order, 'state'));
let side = this.safeString (order, 'side');
if (side === 'BID') {
side = 'buy';
} else {
side = 'sell';
}
const lastTradeTimestamp = this.parse8601 (this.safeString (order, 'updated_at'));
return this.safeOrder ({
'info': order,
'id': id,
'clientOrderId': undefined,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': lastTradeTimestamp,
'symbol': symbol,
'type': undefined,
'timeInForce': undefined,
'postOnly': undefined,
'side': side,
'price': price,
'stopPrice': undefined,
'amount': amount,
'cost': undefined,
'average': average,
'filled': filled,
'remaining': undefined,
'status': status,
'fee': undefined,
'trades': undefined,
}, market);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
side = (side === 'buy') ? 'BID' : 'ASK';
const uppercaseType = type.toUpperCase ();
const request = {
'asset_pair_name': market['id'], // asset pair name BTC-USDT, required
'side': side, // order side one of "ASK"/"BID", required
'amount': this.amountToPrecision (symbol, amount), // order amount, string, required
// 'price': this.priceToPrecision (symbol, price), // order price, string, required
'type': uppercaseType,
// 'operator': 'GTE', // stop orders only, GTE greater than and equal, LTE less than and equal
// 'immediate_or_cancel': false, // limit orders only, must be false when post_only is true
// 'post_only': false, // limit orders only, must be false when immediate_or_cancel is true
};
if (uppercaseType === 'LIMIT') {
request['price'] = this.priceToPrecision (symbol, price);
} else {
const isStopLimit = (uppercaseType === 'STOP_LIMIT');
const isStopMarket = (uppercaseType === 'STOP_MARKET');
if (isStopLimit || isStopMarket) {
const stopPrice = this.safeNumber2 (params, 'stop_price', 'stopPrice');
if (stopPrice === undefined) {
throw new ArgumentsRequired (this.id + ' createOrder() requires a stop_price parameter');
}
request['stop_price'] = this.priceToPrecision (symbol, stopPrice);
params = this.omit (params, [ 'stop_price', 'stopPrice' ]);
}
if (isStopLimit) {
request['price'] = this.priceToPrecision (symbol, price);
}
}
const response = await this.privatePostOrders (this.extend (request, params));
//
// {
// "id": 10,
// "asset_pair_name": "EOS-BTC",
// "price": "10.00",
// "amount": "10.00",
// "filled_amount": "9.0",
// "avg_deal_price": "12.0",
// "side": "ASK",
// "state": "FILLED",
// "created_at":"2019-01-29T06:05:56Z",
// "updated_at":"2019-01-29T06:05:56Z"
// }
//
const order = this.safeValue (response, 'data');
return this.parseOrder (order, market);
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
const request = { 'id': id };
const response = await this.privatePostOrdersIdCancel (this.extend (request, params));
// {
// "id": 10,
// "asset_pair_name": "EOS-BTC",
// "price": "10.00",
// "amount": "10.00",
// "filled_amount": "9.0",
// "avg_deal_price": "12.0",
// "side": "ASK",
// "state": "CANCELLED",
// "created_at":"2019-01-29T06:05:56Z",
// "updated_at":"2019-01-29T06:05:56Z"
// }
const order = this.safeValue (response, 'data');
return this.parseOrder (order);
}
async cancelAllOrders (symbol = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'asset_pair_name': market['id'],
};
const response = await this.privatePostOrdersCancel (this.extend (request, params));
//
// {
// "code":0,
// "data": {
// "cancelled":[
// 58272370,
// 58272377
// ],
// "failed": []
// }
// }
//
return response;
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
const request = { 'id': id };
const response = await this.privateGetOrdersId (this.extend (request, params));
const order = this.safeValue (response, 'data', {});
return this.parseOrder (order);
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrders() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'asset_pair_name': market['id'],
// 'page_token': 'dxzef', // request page after this page token
// 'side': 'ASK', // 'ASK' or 'BID', optional
// 'state': 'FILLED', // 'CANCELLED', 'FILLED', 'PENDING'
// 'limit' 20, // default 20, max 200
};
if (limit !== undefined) {
request['limit'] = limit; // default 20, max 200
}
const response = await this.privateGetOrders (this.extend (request, params));
//
// {
// "code":0,
// "data": [
// {
// "id": 10,
// "asset_pair_name": "ETH-BTC",
// "price": "10.00",
// "amount": "10.00",
// "filled_amount": "9.0",
// "avg_deal_price": "12.0",
// "side": "ASK",
// "state": "FILLED",
// "created_at":"2019-01-29T06:05:56Z",
// "updated_at":"2019-01-29T06:05:56Z",
// },
// ],
// "page_token":"dxzef",
// }
//
const orders = this.safeValue (response, 'data', []);
return this.parseOrders (orders, market, since, limit);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchMyTrades() requires a symbol argument');
}
const market = this.market (symbol);
const request = {
'asset_pair_name': market['id'],
// 'page_token': 'dxzef', // request page after this page token
};
if (limit !== undefined) {
request['limit'] = limit; // default 20, max 200
}
const response = await this.privateGetTrades (this.extend (request, params));
//
// {
// "code": 0,
// "data": [
// {
// "id": 10854280,
// "asset_pair_name": "XIN-USDT",
// "price": "70",
// "amount": "1",
// "taker_side": "ASK",
// "maker_order_id": 58284908,
// "taker_order_id": 58284909,
// "maker_fee": "0.0008",
// "taker_fee": "0.07",
// "side": "SELF_TRADING",
// "inserted_at": "2019-04-16T12:00:01Z"
// },
// {
// "id": 10854263,
// "asset_pair_name": "XIN-USDT",
// "price": "75.7",
// "amount": "12.743149",
// "taker_side": "BID",
// "maker_order_id": null,
// "taker_order_id": 58284888,
// "maker_fee": null,
// "taker_fee": "0.0025486298",
// "side": "BID",
// "inserted_at": "2019-04-15T06:20:57Z"
// }
// ],
// "page_token":"dxfv"
// }
//
const trades = this.safeValue (response, 'data', []);
return this.parseTrades (trades, market, since, limit);
}
parseOrderStatus (status) {
const statuses = {
'PENDING': 'open',
'FILLED': 'closed',
'CANCELLED': 'canceled',
};
return this.safeString (statuses, status);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
const request = {
'state': 'PENDING',
};
return await this.fetchOrders (symbol, since, limit, this.extend (request, params));
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
const request = {
'state': 'FILLED',
};
return await this.fetchOrders (symbol, since, limit, this.extend (request, params));
}
nonce () {
return this.microseconds () * 1000;
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
const query = this.omit (params, this.extractParams (path));
const baseUrl = this.implodeHostname (this.urls['api'][api]);
let url = baseUrl + '/' + this.implodeParams (path, params);
if (api === 'public') {
if (Object.keys (query).length) {
url += '?' + this.urlencode (query);
}
} else {
this.checkRequiredCredentials ();
const nonce = this.nonce ().toString ();
const request = {
'type': 'OpenAPIV2',
'sub': this.apiKey,
'nonce': nonce,
// 'recv_window': '30', // default 30
};
const jwt = this.jwt (request, this.encode (this.secret));
headers = {
'Authorization': 'Bearer ' + jwt,
};
if (method === 'GET') {
if (Object.keys (query).length) {
url += '?' + this.urlencode (query);
}
} else if (method === 'POST') {
headers['Content-Type'] = 'application/json';
body = this.json (query);
}
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'asset_symbol': currency['id'],
};
const response = await this.privateGetAssetsAssetSymbolAddress (this.extend (request, params));
//
// the actual response format is not the same as the documented one
// the data key contains an array in the actual response
//
// {
// "code":0,
// "message":"",
// "data":[
// {
// "id":5521878,
// "chain":"Bitcoin",
// "value":"1GbmyKoikhpiQVZ1C9sbF17mTyvBjeobVe",
// "memo":""
// }
// ]
// }
//
const data = this.safeValue (response, 'data', []);
const dataLength = data.length;
if (dataLength < 1) {
throw new ExchangeError (this.id + ' fetchDepositAddress() returned empty address response');
}
const firstElement = data[0];
const address = this.safeString (firstElement, 'value');
const tag = this.safeString (firstElement, 'memo');
this.checkAddress (address);
return {
'currency': code,
'address': address,
'tag': tag,
'network': undefined,
'info': response,
};
}
parseTransactionStatus (status) {
const statuses = {
// what are other statuses here?
'WITHHOLD': 'ok', // deposits
'UNCONFIRMED': 'pending',
'CONFIRMED': 'ok', // withdrawals
'COMPLETED': 'ok',
'PENDING': 'pending',
};
return this.safeString (statuses, status, status);
}
parseTransaction (transaction, currency = undefined) {
//
// fetchDeposits
//
// {
// "amount": "25.0",
// "asset_symbol": "BTS"
// "confirms": 100,
// "id": 5,
// "inserted_at": "2018-02-16T11:39:58.000Z",
// "is_internal": false,
// "kind": "default",
// "memo": "",
// "state": "WITHHOLD",
// "txid": "72e03037d144dae3d32b68b5045462b1049a0755",
// "updated_at": "2018-11-09T10:20:09.000Z",
// }
//
// fetchWithdrawals
//
// {
// "amount": "5",
// "asset_symbol": "ETH",
// "completed_at": "2018-03-15T16:13:45.610463Z",
// "customer_id": "10",
// "id": 10,
// "inserted_at": "2018-03-15T16:13:45.610463Z",
// "is_internal": true,
// "note": "2018-03-15T16:13:45.610463Z",
// "state": "CONFIRMED",
// "target_address": "0x4643bb6b393ac20a6175c713175734a72517c63d6f7"
// "txid": "0x4643bb6b393ac20a6175c713175734a72517c63d6f73a3ca90a15356f2e967da0",
// }
//
// withdraw
//
// {
// "id":1077391,
// "customer_id":1082679,
// "amount":"21.9000000000000000",
// "txid":"",
// "is_internal":false,
// "kind":"on_chain",
// "state":"PENDING",
// "inserted_at":"2020-06-03T00:50:57+00:00",
// "updated_at":"2020-06-03T00:50:57+00:00",
// "memo":"",
// "target_address":"rDYtYT3dBeuw376rvHqoZBKW3UmvguoBAf",
// "fee":"0.1000000000000000",
// "asset_symbol":"XRP"
// }
//
const currencyId = this.safeString (transaction, 'asset_symbol');
const code = this.safeCurrencyCode (currencyId);
const id = this.safeInteger (transaction, 'id');
const amount = this.safeNumber (transaction, 'amount');
const status = this.parseTransactionStatus (this.safeString (transaction, 'state'));
const timestamp = this.parse8601 (this.safeString (transaction, 'inserted_at'));
const updated = this.parse8601 (this.safeString2 (transaction, 'updated_at', 'completed_at'));
const txid = this.safeString (transaction, 'txid');
const address = this.safeString (transaction, 'target_address');
const tag = this.safeString (transaction, 'memo');
const type = ('customer_id' in transaction) ? 'deposit' : 'withdrawal';
return {
'info': transaction,
'id': id,
'txid': txid,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'network': undefined,
'addressFrom': undefined,
'address': undefined,
'addressTo': address,
'tagFrom': undefined,
'tag': tag,
'tagTo': undefined,
'type': type,
'amount': amount,
'currency': code,
'status': status,
'updated': updated,
'fee': undefined,
};
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'page_token': 'dxzef', // request page after this page token
// 'limit': 50, // optional, default 50
// 'kind': 'string', // optional - air_drop, big_holder_dividend, default, eosc_to_eos, internal, equally_airdrop, referral_mining, one_holder_dividend, single_customer, snapshotted_airdrop, trade_mining
// 'asset_symbol': 'BTC', // optional
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['asset_symbol'] = currency['id'];
}
if (limit !== undefined) {
request['limit'] = limit; // default 50
}
const response = await this.privateGetDeposits (this.extend (request, params));
//
// {
// "code": 0,
// "page_token": "NQ==",
// "data": [
// {
// "id": 5,
// "amount": "25.0",
// "confirms": 100,
// "txid": "72e03037d144dae3d32b68b5045462b1049a0755",
// "is_internal": false,
// "inserted_at": "2018-02-16T11:39:58.000Z",
// "updated_at": "2018-11-09T10:20:09.000Z",
// "kind": "default",
// "memo": "",
// "state": "WITHHOLD",
// "asset_symbol": "BTS"
// }
// ]
// }
//
const deposits = this.safeValue (response, 'data', []);
return this.parseTransactions (deposits, code, since, limit);
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'page_token': 'dxzef', // request page after this page token
// 'limit': 50, // optional, default 50
// 'kind': 'string', // optional - air_drop, big_holder_dividend, default, eosc_to_eos, internal, equally_airdrop, referral_mining, one_holder_dividend, single_customer, snapshotted_airdrop, trade_mining
// 'asset_symbol': 'BTC', // optional
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['asset_symbol'] = currency['id'];
}
if (limit !== undefined) {
request['limit'] = limit; // default 50
}
const response = await this.privateGetWithdrawals (this.extend (request, params));
//
// {
// "code": 0,
// "data": [
// {
// "id": 10,
// "customer_id": "10",
// "asset_symbol": "ETH",
// "amount": "5",
// "state": "CONFIRMED",
// "note": "2018-03-15T16:13:45.610463Z",
// "txid": "0x4643bb6b393ac20a6175c713175734a72517c63d6f73a3ca90a15356f2e967da0",
// "completed_at": "2018-03-15T16:13:45.610463Z",
// "inserted_at": "2018-03-15T16:13:45.610463Z",
// "is_internal": true,
// "target_address": "0x4643bb6b393ac20a6175c713175734a72517c63d6f7"
// }
// ],
// "page_token":"dxvf"
// }
//
const withdrawals = this.safeValue (response, 'data', []);
return this.parseTransactions (withdrawals, code, since, limit);
}
async transfer (code, amount, fromAccount, toAccount, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const accountsByType = this.safeValue (this.options, 'accountsByType', {});
const fromId = this.safeString (accountsByType, fromAccount, fromAccount);
const toId = this.safeString (accountsByType, toAccount, toAccount);
const type = this.safeString (params, 'type');
const subAccount = this.safeString (params, 'sub_account');
const guid = this.safeString (params, 'guid', this.uuid ());
const request = {
'symbol': currency['id'],
'amount': this.currencyToPrecision (code, amount),
'from': fromId,
'to': toId,
'guid': guid,
'type': type,
};
if (type !== undefined) {
request['type'] = type;
}
if (subAccount !== undefined) {
request['sub_account'] = subAccount;
}
const response = await this.privatePostTransfer (this.extend (request, params));
//
// {
// "code": 0,
// "data": null
// }
//
const transfer = this.parseTransfer (response, currency);
const transferOptions = this.safeValue (this.options, 'transfer', {});
const fillResponseFromRequest = this.safeValue (transferOptions, 'fillResponseFromRequest', true);
if (fillResponseFromRequest) {
transfer['fromAccount'] = fromAccount;
transfer['toAccount'] = toAccount;
transfer['amount'] = amount;
transfer['id'] = guid;
}
return transfer;
}
parseTransfer (transfer, currency = undefined) {
//
// {
// "code": 0,
// "data": null
// }
//
const code = this.safeNumber (transfer, 'code');
return {
'info': transfer,
'id': undefined,
'timestamp': undefined,
'datetime': undefined,
'currency': code,
'amount': undefined,
'fromAccount': undefined,
'toAccount': undefined,
'status': this.parseTransferStatus (code),
};
}
parseTransferStatus (status) {
const statuses = {
'0': 'ok',
};
return this.safeString (statuses, status, 'failed');
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
[ tag, params ] = this.handleWithdrawTagAndParams (tag, params);
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'symbol': currency['id'],
'target_address': address,
'amount': this.currencyToPrecision (code, amount),
};
if (tag !== undefined) {
request['memo'] = tag;
}
// requires write permission on the wallet
const response = await this.privatePostWithdrawals (this.extend (request, params));
//
// {
// "code":0,
// "message":"",
// "data":{
// "id":1077391,
// "customer_id":1082679,
// "amount":"21.9000000000000000",
// "txid":"",
// "is_internal":false,
// "kind":"on_chain",
// "state":"PENDING",
// "inserted_at":"2020-06-03T00:50:57+00:00",
// "updated_at":"2020-06-03T00:50:57+00:00",
// "memo":"",
// "target_address":"rDYtYT3dBeuw376rvHqoZBKW3UmvguoBAf",
// "fee":"0.1000000000000000",
// "asset_symbol":"XRP"
// }
// }
//
const data = this.safeValue (response, 'data', {});
return this.parseTransaction (data, currency);
}
handleErrors (httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) {
if (response === undefined) {
return; // fallback to default error handler
}
//
// {"code":10013,"message":"Resource not found"}
// {"code":40004,"message":"invalid jwt"}
//
const code = this.safeString (response, 'code');
const message = this.safeString (response, 'message');
if (code !== '0') {
const feedback = this.id + ' ' + body;
this.throwExactlyMatchedException (this.exceptions['exact'], message, feedback);
this.throwExactlyMatchedException (this.exceptions['exact'], code, feedback);
this.throwBroadlyMatchedException (this.exceptions['broad'], message, feedback);
throw new ExchangeError (feedback); // unknown message
}
}
};
| js/bigone.js | 'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError, ArgumentsRequired, AuthenticationError, InsufficientFunds, PermissionDenied, BadRequest, BadSymbol, RateLimitExceeded, InvalidOrder } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class bigone extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bigone',
'name': 'BigONE',
'countries': [ 'CN' ],
'version': 'v3',
'rateLimit': 1200, // 500 request per 10 minutes
'has': {
'CORS': undefined,
'spot': true,
'margin': undefined, // has but unimplemented
'swap': undefined, // has but unimplemented
'future': undefined, // has but unimplemented
'option': undefined,
'cancelAllOrders': true,
'cancelOrder': true,
'createOrder': true,
'fetchBalance': true,
'fetchClosedOrders': true,
'fetchDepositAddress': true,
'fetchDeposits': true,
'fetchMarkets': true,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTime': true,
'fetchTrades': true,
'fetchTradingFee': false,
'fetchTradingFees': false,
'fetchWithdrawals': true,
'transfer': true,
'withdraw': true,
},
'timeframes': {
'1m': 'min1',
'5m': 'min5',
'15m': 'min15',
'30m': 'min30',
'1h': 'hour1',
'3h': 'hour3',
'4h': 'hour4',
'6h': 'hour6',
'12h': 'hour12',
'1d': 'day1',
'1w': 'week1',
'1M': 'month1',
},
'hostname': 'big.one', // or 'bigone.com'
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/69354403-1d532180-0c91-11ea-88ed-44c06cefdf87.jpg',
'api': {
'public': 'https://{hostname}/api/v3',
'private': 'https://{hostname}/api/v3/viewer',
},
'www': 'https://big.one',
'doc': 'https://open.big.one/docs/api.html',
'fees': 'https://bigone.zendesk.com/hc/en-us/articles/115001933374-BigONE-Fee-Policy',
'referral': 'https://b1.run/users/new?code=D3LLBVFT',
},
'api': {
'public': {
'get': [
'ping',
'asset_pairs',
'asset_pairs/{asset_pair_name}/depth',
'asset_pairs/{asset_pair_name}/trades',
'asset_pairs/{asset_pair_name}/ticker',
'asset_pairs/{asset_pair_name}/candles',
'asset_pairs/tickers',
],
},
'private': {
'get': [
'accounts',
'fund/accounts',
'assets/{asset_symbol}/address',
'orders',
'orders/{id}',
'orders/multi',
'trades',
'withdrawals',
'deposits',
],
'post': [
'orders',
'orders/{id}/cancel',
'orders/cancel',
'withdrawals',
'transfer',
],
},
},
'fees': {
'trading': {
'maker': this.parseNumber ('0.001'),
'taker': this.parseNumber ('0.001'),
},
'funding': {
'withdraw': {},
},
},
'options': {
'accountsByType': {
'spot': 'SPOT',
'funding': 'FUND',
'future': 'CONTRACT',
'swap': 'CONTRACT',
},
'accountsById': {
'SPOT': 'spot',
'FUND': 'funding',
'CONTRACT': 'future',
},
'transfer': {
'fillResponseFromRequest': true,
},
},
'exceptions': {
'exact': {
'10001': BadRequest, // syntax error
'10005': ExchangeError, // internal error
"Amount's scale must greater than AssetPair's base scale": InvalidOrder,
"Price mulit with amount should larger than AssetPair's min_quote_value": InvalidOrder,
'10007': BadRequest, // parameter error, {"code":10007,"message":"Amount's scale must greater than AssetPair's base scale"}
'10011': ExchangeError, // system error
'10013': BadSymbol, // {"code":10013,"message":"Resource not found"}
'10014': InsufficientFunds, // {"code":10014,"message":"Insufficient funds"}
'10403': PermissionDenied, // permission denied
'10429': RateLimitExceeded, // too many requests
'40004': AuthenticationError, // {"code":40004,"message":"invalid jwt"}
'40103': AuthenticationError, // invalid otp code
'40104': AuthenticationError, // invalid asset pin code
'40301': PermissionDenied, // {"code":40301,"message":"Permission denied withdrawal create"}
'40302': ExchangeError, // already requested
'40601': ExchangeError, // resource is locked
'40602': ExchangeError, // resource is depleted
'40603': InsufficientFunds, // insufficient resource
'40605': InvalidOrder, // {"code":40605,"message":"Price less than the minimum order price"}
'40120': InvalidOrder, // Order is in trading
'40121': InvalidOrder, // Order is already cancelled or filled
'60100': BadSymbol, // {"code":60100,"message":"Asset pair is suspended"}
},
'broad': {
},
},
'commonCurrencies': {
'CRE': 'Cybereits',
'FXT': 'FXTTOKEN',
'FREE': 'FreeRossDAO',
'MBN': 'Mobilian Coin',
'ONE': 'BigONE Token',
},
});
}
async fetchMarkets (params = {}) {
const response = await this.publicGetAssetPairs (params);
//
// {
// "code":0,
// "data":[
// {
// "id":"01e48809-b42f-4a38-96b1-c4c547365db1",
// "name":"PCX-BTC",
// "quote_scale":7,
// "quote_asset":{
// "id":"0df9c3c3-255a-46d7-ab82-dedae169fba9",
// "symbol":"BTC",
// "name":"Bitcoin",
// },
// "base_asset":{
// "id":"405484f7-4b03-4378-a9c1-2bd718ecab51",
// "symbol":"PCX",
// "name":"ChainX",
// },
// "base_scale":3,
// "min_quote_value":"0.0001",
// "max_quote_value":"35"
// },
// ]
// }
//
const markets = this.safeValue (response, 'data', []);
const result = [];
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const id = this.safeString (market, 'name');
const uuid = this.safeString (market, 'id');
const baseAsset = this.safeValue (market, 'base_asset', {});
const quoteAsset = this.safeValue (market, 'quote_asset', {});
const baseId = this.safeString (baseAsset, 'symbol');
const quoteId = this.safeString (quoteAsset, 'symbol');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const entry = {
'id': id,
'uuid': uuid,
'symbol': base + '/' + quote,
'base': base,
'quote': quote,
'settle': undefined,
'baseId': baseId,
'quoteId': quoteId,
'settleId': undefined,
'type': 'spot',
'spot': true,
'margin': false,
'swap': false,
'future': false,
'option': false,
'active': true,
'contract': false,
'linear': undefined,
'inverse': undefined,
'contractSize': undefined,
'expiry': undefined,
'expiryDatetime': undefined,
'strike': undefined,
'optionType': undefined,
'precision': {
'amount': this.safeInteger (market, 'base_scale'),
'price': this.safeInteger (market, 'quote_scale'),
},
'limits': {
'leverage': {
'min': undefined,
'max': undefined,
},
'amount': {
'min': undefined,
'max': undefined,
},
'price': {
'min': undefined,
'max': undefined,
},
'cost': {
'min': this.safeNumber (market, 'min_quote_value'),
'max': this.safeNumber (market, 'max_quote_value'),
},
},
'info': market,
};
result.push (entry);
}
return result;
}
async loadMarkets (reload = false, params = {}) {
const markets = await super.loadMarkets (reload, params);
let marketsByUuid = this.safeValue (this.options, 'marketsByUuid');
if ((marketsByUuid === undefined) || reload) {
marketsByUuid = {};
for (let i = 0; i < this.symbols.length; i++) {
const symbol = this.symbols[i];
const market = this.markets[symbol];
const uuid = this.safeString (market, 'uuid');
marketsByUuid[uuid] = market;
}
this.options['marketsByUuid'] = marketsByUuid;
}
return markets;
}
parseTicker (ticker, market = undefined) {
//
// {
// "asset_pair_name":"ETH-BTC",
// "bid":{"price":"0.021593","order_count":1,"quantity":"0.20936"},
// "ask":{"price":"0.021613","order_count":1,"quantity":"2.87064"},
// "open":"0.021795",
// "high":"0.021795",
// "low":"0.021471",
// "close":"0.021613",
// "volume":"117078.90431",
// "daily_change":"-0.000182"
// }
//
const marketId = this.safeString (ticker, 'asset_pair_name');
const symbol = this.safeSymbol (marketId, market, '-');
const timestamp = undefined;
const close = this.safeString (ticker, 'close');
const bid = this.safeValue (ticker, 'bid', {});
const ask = this.safeValue (ticker, 'ask', {});
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeString (ticker, 'high'),
'low': this.safeString (ticker, 'low'),
'bid': this.safeString (bid, 'price'),
'bidVolume': this.safeString (bid, 'quantity'),
'ask': this.safeString (ask, 'price'),
'askVolume': this.safeString (ask, 'quantity'),
'vwap': undefined,
'open': this.safeString (ticker, 'open'),
'close': close,
'last': close,
'previousClose': undefined,
'change': this.safeString (ticker, 'daily_change'),
'percentage': undefined,
'average': undefined,
'baseVolume': this.safeString (ticker, 'volume'),
'quoteVolume': undefined,
'info': ticker,
}, market, false);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'asset_pair_name': market['id'],
};
const response = await this.publicGetAssetPairsAssetPairNameTicker (this.extend (request, params));
//
// {
// "code":0,
// "data":{
// "asset_pair_name":"ETH-BTC",
// "bid":{"price":"0.021593","order_count":1,"quantity":"0.20936"},
// "ask":{"price":"0.021613","order_count":1,"quantity":"2.87064"},
// "open":"0.021795",
// "high":"0.021795",
// "low":"0.021471",
// "close":"0.021613",
// "volume":"117078.90431",
// "daily_change":"-0.000182"
// }
// }
//
const ticker = this.safeValue (response, 'data', {});
return this.parseTicker (ticker, market);
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (symbols !== undefined) {
const ids = this.marketIds (symbols);
request['pair_names'] = ids.join (',');
}
const response = await this.publicGetAssetPairsTickers (this.extend (request, params));
//
// {
// "code":0,
// "data":[
// {
// "asset_pair_name":"PCX-BTC",
// "bid":{"price":"0.000234","order_count":1,"quantity":"0.518"},
// "ask":{"price":"0.0002348","order_count":1,"quantity":"2.348"},
// "open":"0.0002343",
// "high":"0.0002348",
// "low":"0.0002162",
// "close":"0.0002348",
// "volume":"12887.016",
// "daily_change":"0.0000005"
// },
// {
// "asset_pair_name":"GXC-USDT",
// "bid":{"price":"0.5054","order_count":1,"quantity":"40.53"},
// "ask":{"price":"0.5055","order_count":1,"quantity":"38.53"},
// "open":"0.5262",
// "high":"0.5323",
// "low":"0.5055",
// "close":"0.5055",
// "volume":"603963.05",
// "daily_change":"-0.0207"
// }
// ]
// }
//
const tickers = this.safeValue (response, 'data', []);
const result = {};
for (let i = 0; i < tickers.length; i++) {
const ticker = this.parseTicker (tickers[i]);
const symbol = ticker['symbol'];
result[symbol] = ticker;
}
return this.filterByArray (result, 'symbol', symbols);
}
async fetchTime (params = {}) {
const response = await this.publicGetPing (params);
//
// {
// "data": {
// "timestamp": 1527665262168391000
// }
// }
//
const data = this.safeValue (response, 'data', {});
const timestamp = this.safeInteger (data, 'timestamp');
return parseInt (timestamp / 1000000);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'asset_pair_name': market['id'],
};
if (limit !== undefined) {
request['limit'] = limit; // default 50, max 200
}
const response = await this.publicGetAssetPairsAssetPairNameDepth (this.extend (request, params));
//
// {
// "code":0,
// "data": {
// "asset_pair_name": "EOS-BTC",
// "bids": [
// { "price": "42", "order_count": 4, "quantity": "23.33363711" }
// ],
// "asks": [
// { "price": "45", "order_count": 2, "quantity": "4193.3283464" }
// ]
// }
// }
//
const orderbook = this.safeValue (response, 'data', {});
return this.parseOrderBook (orderbook, symbol, undefined, 'bids', 'asks', 'price', 'quantity');
}
parseTrade (trade, market = undefined) {
//
// fetchTrades (public)
//
// {
// "id": 38199941,
// "price": "3378.67",
// "amount": "0.019812",
// "taker_side": "ASK",
// "created_at": "2019-01-29T06:05:56Z"
// }
//
// fetchMyTrades (private)
//
// {
// "id": 10854280,
// "asset_pair_name": "XIN-USDT",
// "price": "70",
// "amount": "1",
// "taker_side": "ASK",
// "maker_order_id": 58284908,
// "taker_order_id": 58284909,
// "maker_fee": "0.0008",
// "taker_fee": "0.07",
// "side": "SELF_TRADING",
// "inserted_at": "2019-04-16T12:00:01Z"
// },
//
// {
// "id": 10854263,
// "asset_pair_name": "XIN-USDT",
// "price": "75.7",
// "amount": "12.743149",
// "taker_side": "BID",
// "maker_order_id": null,
// "taker_order_id": 58284888,
// "maker_fee": null,
// "taker_fee": "0.0025486298",
// "side": "BID",
// "inserted_at": "2019-04-15T06:20:57Z"
// }
//
const timestamp = this.parse8601 (this.safeString2 (trade, 'created_at', 'inserted_at'));
const priceString = this.safeString (trade, 'price');
const amountString = this.safeString (trade, 'amount');
const marketId = this.safeString (trade, 'asset_pair_name');
market = this.safeMarket (marketId, market, '-');
let side = this.safeString (trade, 'side');
const takerSide = this.safeString (trade, 'taker_side');
let takerOrMaker = undefined;
if ((takerSide !== undefined) && (side !== undefined) && (side !== 'SELF_TRADING')) {
takerOrMaker = (takerSide === side) ? 'taker' : 'maker';
}
if (side === undefined) {
// taker side is not related to buy/sell side
// the following code is probably a mistake
side = (takerSide === 'ASK') ? 'sell' : 'buy';
} else {
if (side === 'BID') {
side = 'buy';
} else if (side === 'ASK') {
side = 'sell';
}
}
const makerOrderId = this.safeString (trade, 'maker_order_id');
const takerOrderId = this.safeString (trade, 'taker_order_id');
let orderId = undefined;
if (makerOrderId !== undefined) {
if (takerOrderId !== undefined) {
orderId = [ makerOrderId, takerOrderId ];
} else {
orderId = makerOrderId;
}
} else if (takerOrderId !== undefined) {
orderId = takerOrderId;
}
const id = this.safeString (trade, 'id');
const result = {
'id': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': market['symbol'],
'order': orderId,
'type': 'limit',
'side': side,
'takerOrMaker': takerOrMaker,
'price': priceString,
'amount': amountString,
'cost': undefined,
'info': trade,
};
let makerCurrencyCode = undefined;
let takerCurrencyCode = undefined;
if (takerOrMaker !== undefined) {
if (side === 'buy') {
if (takerOrMaker === 'maker') {
makerCurrencyCode = market['base'];
takerCurrencyCode = market['quote'];
} else {
makerCurrencyCode = market['quote'];
takerCurrencyCode = market['base'];
}
} else {
if (takerOrMaker === 'maker') {
makerCurrencyCode = market['quote'];
takerCurrencyCode = market['base'];
} else {
makerCurrencyCode = market['base'];
takerCurrencyCode = market['quote'];
}
}
} else if (side === 'SELF_TRADING') {
if (takerSide === 'BID') {
makerCurrencyCode = market['quote'];
takerCurrencyCode = market['base'];
} else if (takerSide === 'ASK') {
makerCurrencyCode = market['base'];
takerCurrencyCode = market['quote'];
}
}
const makerFeeCost = this.safeString (trade, 'maker_fee');
const takerFeeCost = this.safeString (trade, 'taker_fee');
if (makerFeeCost !== undefined) {
if (takerFeeCost !== undefined) {
result['fees'] = [
{ 'cost': makerFeeCost, 'currency': makerCurrencyCode },
{ 'cost': takerFeeCost, 'currency': takerCurrencyCode },
];
} else {
result['fee'] = { 'cost': makerFeeCost, 'currency': makerCurrencyCode };
}
} else if (takerFeeCost !== undefined) {
result['fee'] = { 'cost': takerFeeCost, 'currency': takerCurrencyCode };
} else {
result['fee'] = undefined;
}
return this.safeTrade (result, market);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'asset_pair_name': market['id'],
};
const response = await this.publicGetAssetPairsAssetPairNameTrades (this.extend (request, params));
//
// {
// "code": 0,
// "data": [
// {
// "id": 38199941,
// "price": "3378.67",
// "amount": "0.019812",
// "taker_side": "ASK",
// "created_at": "2019-01-29T06:05:56Z"
// },
// {
// "id": 38199934,
// "price": "3376.14",
// "amount": "0.019384",
// "taker_side": "ASK",
// "created_at": "2019-01-29T06:05:40Z"
// }
// ]
// }
//
const trades = this.safeValue (response, 'data', []);
return this.parseTrades (trades, market, since, limit);
}
parseOHLCV (ohlcv, market = undefined) {
//
// {
// close: '0.021562',
// high: '0.021563',
// low: '0.02156',
// open: '0.021563',
// time: '2019-11-21T07:54:00Z',
// volume: '59.84376'
// }
//
return [
this.parse8601 (this.safeString (ohlcv, 'time')),
this.safeNumber (ohlcv, 'open'),
this.safeNumber (ohlcv, 'high'),
this.safeNumber (ohlcv, 'low'),
this.safeNumber (ohlcv, 'close'),
this.safeNumber (ohlcv, 'volume'),
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (limit === undefined) {
limit = 100; // default 100, max 500
}
const request = {
'asset_pair_name': market['id'],
'period': this.timeframes[timeframe],
'limit': limit,
};
if (since !== undefined) {
// const start = parseInt (since / 1000);
const duration = this.parseTimeframe (timeframe);
const end = this.sum (since, limit * duration * 1000);
request['time'] = this.iso8601 (end);
}
const response = await this.publicGetAssetPairsAssetPairNameCandles (this.extend (request, params));
//
// {
// code: 0,
// data: [
// {
// close: '0.021656',
// high: '0.021658',
// low: '0.021652',
// open: '0.021652',
// time: '2019-11-21T09:30:00Z',
// volume: '53.08664'
// },
// {
// close: '0.021652',
// high: '0.021656',
// low: '0.021652',
// open: '0.021656',
// time: '2019-11-21T09:29:00Z',
// volume: '88.39861'
// },
// ]
// }
//
const data = this.safeValue (response, 'data', []);
return this.parseOHLCVs (data, market, timeframe, since, limit);
}
parseBalance (response) {
const result = {
'info': response,
'timestamp': undefined,
'datetime': undefined,
};
const balances = this.safeValue (response, 'data', []);
for (let i = 0; i < balances.length; i++) {
const balance = balances[i];
const symbol = this.safeString (balance, 'asset_symbol');
const code = this.safeCurrencyCode (symbol);
const account = this.account ();
account['total'] = this.safeString (balance, 'balance');
account['used'] = this.safeString (balance, 'locked_balance');
result[code] = account;
}
return this.safeBalance (result);
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
const type = this.safeString (params, 'type', '');
params = this.omit (params, 'type');
const method = 'privateGet' + this.capitalize (type) + 'Accounts';
const response = await this[method] (params);
//
// {
// "code":0,
// "data":[
// {"asset_symbol":"NKC","balance":"0","locked_balance":"0"},
// {"asset_symbol":"UBTC","balance":"0","locked_balance":"0"},
// {"asset_symbol":"READ","balance":"0","locked_balance":"0"},
// ],
// }
//
return this.parseBalance (response);
}
parseOrder (order, market = undefined) {
//
// {
// "id": 10,
// "asset_pair_name": "EOS-BTC",
// "price": "10.00",
// "amount": "10.00",
// "filled_amount": "9.0",
// "avg_deal_price": "12.0",
// "side": "ASK",
// "state": "FILLED",
// "created_at":"2019-01-29T06:05:56Z",
// "updated_at":"2019-01-29T06:05:56Z",
// }
//
const id = this.safeString (order, 'id');
const marketId = this.safeString (order, 'asset_pair_name');
const symbol = this.safeSymbol (marketId, market, '-');
const timestamp = this.parse8601 (this.safeString (order, 'created_at'));
const price = this.safeString (order, 'price');
const amount = this.safeString (order, 'amount');
const average = this.safeString (order, 'avg_deal_price');
const filled = this.safeString (order, 'filled_amount');
const status = this.parseOrderStatus (this.safeString (order, 'state'));
let side = this.safeString (order, 'side');
if (side === 'BID') {
side = 'buy';
} else {
side = 'sell';
}
const lastTradeTimestamp = this.parse8601 (this.safeString (order, 'updated_at'));
return this.safeOrder ({
'info': order,
'id': id,
'clientOrderId': undefined,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': lastTradeTimestamp,
'symbol': symbol,
'type': undefined,
'timeInForce': undefined,
'postOnly': undefined,
'side': side,
'price': price,
'stopPrice': undefined,
'amount': amount,
'cost': undefined,
'average': average,
'filled': filled,
'remaining': undefined,
'status': status,
'fee': undefined,
'trades': undefined,
}, market);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
side = (side === 'buy') ? 'BID' : 'ASK';
const uppercaseType = type.toUpperCase ();
const request = {
'asset_pair_name': market['id'], // asset pair name BTC-USDT, required
'side': side, // order side one of "ASK"/"BID", required
'amount': this.amountToPrecision (symbol, amount), // order amount, string, required
// 'price': this.priceToPrecision (symbol, price), // order price, string, required
'type': uppercaseType,
// 'operator': 'GTE', // stop orders only, GTE greater than and equal, LTE less than and equal
// 'immediate_or_cancel': false, // limit orders only, must be false when post_only is true
// 'post_only': false, // limit orders only, must be false when immediate_or_cancel is true
};
if (uppercaseType === 'LIMIT') {
request['price'] = this.priceToPrecision (symbol, price);
} else {
const isStopLimit = (uppercaseType === 'STOP_LIMIT');
const isStopMarket = (uppercaseType === 'STOP_MARKET');
if (isStopLimit || isStopMarket) {
const stopPrice = this.safeNumber2 (params, 'stop_price', 'stopPrice');
if (stopPrice === undefined) {
throw new ArgumentsRequired (this.id + ' createOrder() requires a stop_price parameter');
}
request['stop_price'] = this.priceToPrecision (symbol, stopPrice);
params = this.omit (params, [ 'stop_price', 'stopPrice' ]);
}
if (isStopLimit) {
request['price'] = this.priceToPrecision (symbol, price);
}
}
const response = await this.privatePostOrders (this.extend (request, params));
//
// {
// "id": 10,
// "asset_pair_name": "EOS-BTC",
// "price": "10.00",
// "amount": "10.00",
// "filled_amount": "9.0",
// "avg_deal_price": "12.0",
// "side": "ASK",
// "state": "FILLED",
// "created_at":"2019-01-29T06:05:56Z",
// "updated_at":"2019-01-29T06:05:56Z"
// }
//
const order = this.safeValue (response, 'data');
return this.parseOrder (order, market);
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
const request = { 'id': id };
const response = await this.privatePostOrdersIdCancel (this.extend (request, params));
// {
// "id": 10,
// "asset_pair_name": "EOS-BTC",
// "price": "10.00",
// "amount": "10.00",
// "filled_amount": "9.0",
// "avg_deal_price": "12.0",
// "side": "ASK",
// "state": "CANCELLED",
// "created_at":"2019-01-29T06:05:56Z",
// "updated_at":"2019-01-29T06:05:56Z"
// }
const order = this.safeValue (response, 'data');
return this.parseOrder (order);
}
async cancelAllOrders (symbol = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'asset_pair_name': market['id'],
};
const response = await this.privatePostOrdersCancel (this.extend (request, params));
//
// {
// "code":0,
// "data": {
// "cancelled":[
// 58272370,
// 58272377
// ],
// "failed": []
// }
// }
//
return response;
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
const request = { 'id': id };
const response = await this.privateGetOrdersId (this.extend (request, params));
const order = this.safeValue (response, 'data', {});
return this.parseOrder (order);
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrders() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'asset_pair_name': market['id'],
// 'page_token': 'dxzef', // request page after this page token
// 'side': 'ASK', // 'ASK' or 'BID', optional
// 'state': 'FILLED', // 'CANCELLED', 'FILLED', 'PENDING'
// 'limit' 20, // default 20, max 200
};
if (limit !== undefined) {
request['limit'] = limit; // default 20, max 200
}
const response = await this.privateGetOrders (this.extend (request, params));
//
// {
// "code":0,
// "data": [
// {
// "id": 10,
// "asset_pair_name": "ETH-BTC",
// "price": "10.00",
// "amount": "10.00",
// "filled_amount": "9.0",
// "avg_deal_price": "12.0",
// "side": "ASK",
// "state": "FILLED",
// "created_at":"2019-01-29T06:05:56Z",
// "updated_at":"2019-01-29T06:05:56Z",
// },
// ],
// "page_token":"dxzef",
// }
//
const orders = this.safeValue (response, 'data', []);
return this.parseOrders (orders, market, since, limit);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchMyTrades() requires a symbol argument');
}
const market = this.market (symbol);
const request = {
'asset_pair_name': market['id'],
// 'page_token': 'dxzef', // request page after this page token
};
if (limit !== undefined) {
request['limit'] = limit; // default 20, max 200
}
const response = await this.privateGetTrades (this.extend (request, params));
//
// {
// "code": 0,
// "data": [
// {
// "id": 10854280,
// "asset_pair_name": "XIN-USDT",
// "price": "70",
// "amount": "1",
// "taker_side": "ASK",
// "maker_order_id": 58284908,
// "taker_order_id": 58284909,
// "maker_fee": "0.0008",
// "taker_fee": "0.07",
// "side": "SELF_TRADING",
// "inserted_at": "2019-04-16T12:00:01Z"
// },
// {
// "id": 10854263,
// "asset_pair_name": "XIN-USDT",
// "price": "75.7",
// "amount": "12.743149",
// "taker_side": "BID",
// "maker_order_id": null,
// "taker_order_id": 58284888,
// "maker_fee": null,
// "taker_fee": "0.0025486298",
// "side": "BID",
// "inserted_at": "2019-04-15T06:20:57Z"
// }
// ],
// "page_token":"dxfv"
// }
//
const trades = this.safeValue (response, 'data', []);
return this.parseTrades (trades, market, since, limit);
}
parseOrderStatus (status) {
const statuses = {
'PENDING': 'open',
'FILLED': 'closed',
'CANCELLED': 'canceled',
};
return this.safeString (statuses, status);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
const request = {
'state': 'PENDING',
};
return await this.fetchOrders (symbol, since, limit, this.extend (request, params));
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
const request = {
'state': 'FILLED',
};
return await this.fetchOrders (symbol, since, limit, this.extend (request, params));
}
nonce () {
return this.microseconds () * 1000;
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
const query = this.omit (params, this.extractParams (path));
const baseUrl = this.implodeHostname (this.urls['api'][api]);
let url = baseUrl + '/' + this.implodeParams (path, params);
if (api === 'public') {
if (Object.keys (query).length) {
url += '?' + this.urlencode (query);
}
} else {
this.checkRequiredCredentials ();
const nonce = this.nonce ().toString ();
const request = {
'type': 'OpenAPIV2',
'sub': this.apiKey,
'nonce': nonce,
// 'recv_window': '30', // default 30
};
const jwt = this.jwt (request, this.encode (this.secret));
headers = {
'Authorization': 'Bearer ' + jwt,
};
if (method === 'GET') {
if (Object.keys (query).length) {
url += '?' + this.urlencode (query);
}
} else if (method === 'POST') {
headers['Content-Type'] = 'application/json';
body = this.json (query);
}
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'asset_symbol': currency['id'],
};
const response = await this.privateGetAssetsAssetSymbolAddress (this.extend (request, params));
//
// the actual response format is not the same as the documented one
// the data key contains an array in the actual response
//
// {
// "code":0,
// "message":"",
// "data":[
// {
// "id":5521878,
// "chain":"Bitcoin",
// "value":"1GbmyKoikhpiQVZ1C9sbF17mTyvBjeobVe",
// "memo":""
// }
// ]
// }
//
const data = this.safeValue (response, 'data', []);
const dataLength = data.length;
if (dataLength < 1) {
throw new ExchangeError (this.id + ' fetchDepositAddress() returned empty address response');
}
const firstElement = data[0];
const address = this.safeString (firstElement, 'value');
const tag = this.safeString (firstElement, 'memo');
this.checkAddress (address);
return {
'currency': code,
'address': address,
'tag': tag,
'network': undefined,
'info': response,
};
}
parseTransactionStatus (status) {
const statuses = {
// what are other statuses here?
'WITHHOLD': 'ok', // deposits
'UNCONFIRMED': 'pending',
'CONFIRMED': 'ok', // withdrawals
'COMPLETED': 'ok',
'PENDING': 'pending',
};
return this.safeString (statuses, status, status);
}
parseTransaction (transaction, currency = undefined) {
//
// fetchDeposits
//
// {
// "amount": "25.0",
// "asset_symbol": "BTS"
// "confirms": 100,
// "id": 5,
// "inserted_at": "2018-02-16T11:39:58.000Z",
// "is_internal": false,
// "kind": "default",
// "memo": "",
// "state": "WITHHOLD",
// "txid": "72e03037d144dae3d32b68b5045462b1049a0755",
// "updated_at": "2018-11-09T10:20:09.000Z",
// }
//
// fetchWithdrawals
//
// {
// "amount": "5",
// "asset_symbol": "ETH",
// "completed_at": "2018-03-15T16:13:45.610463Z",
// "customer_id": "10",
// "id": 10,
// "inserted_at": "2018-03-15T16:13:45.610463Z",
// "is_internal": true,
// "note": "2018-03-15T16:13:45.610463Z",
// "state": "CONFIRMED",
// "target_address": "0x4643bb6b393ac20a6175c713175734a72517c63d6f7"
// "txid": "0x4643bb6b393ac20a6175c713175734a72517c63d6f73a3ca90a15356f2e967da0",
// }
//
// withdraw
//
// {
// "id":1077391,
// "customer_id":1082679,
// "amount":"21.9000000000000000",
// "txid":"",
// "is_internal":false,
// "kind":"on_chain",
// "state":"PENDING",
// "inserted_at":"2020-06-03T00:50:57+00:00",
// "updated_at":"2020-06-03T00:50:57+00:00",
// "memo":"",
// "target_address":"rDYtYT3dBeuw376rvHqoZBKW3UmvguoBAf",
// "fee":"0.1000000000000000",
// "asset_symbol":"XRP"
// }
//
const currencyId = this.safeString (transaction, 'asset_symbol');
const code = this.safeCurrencyCode (currencyId);
const id = this.safeInteger (transaction, 'id');
const amount = this.safeNumber (transaction, 'amount');
const status = this.parseTransactionStatus (this.safeString (transaction, 'state'));
const timestamp = this.parse8601 (this.safeString (transaction, 'inserted_at'));
const updated = this.parse8601 (this.safeString2 (transaction, 'updated_at', 'completed_at'));
const txid = this.safeString (transaction, 'txid');
const address = this.safeString (transaction, 'target_address');
const tag = this.safeString (transaction, 'memo');
const type = ('customer_id' in transaction) ? 'deposit' : 'withdrawal';
return {
'info': transaction,
'id': id,
'txid': txid,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'network': undefined,
'addressFrom': undefined,
'address': undefined,
'addressTo': address,
'tagFrom': undefined,
'tag': tag,
'tagTo': undefined,
'type': type,
'amount': amount,
'currency': code,
'status': status,
'updated': updated,
'fee': undefined,
};
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'page_token': 'dxzef', // request page after this page token
// 'limit': 50, // optional, default 50
// 'kind': 'string', // optional - air_drop, big_holder_dividend, default, eosc_to_eos, internal, equally_airdrop, referral_mining, one_holder_dividend, single_customer, snapshotted_airdrop, trade_mining
// 'asset_symbol': 'BTC', // optional
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['asset_symbol'] = currency['id'];
}
if (limit !== undefined) {
request['limit'] = limit; // default 50
}
const response = await this.privateGetDeposits (this.extend (request, params));
//
// {
// "code": 0,
// "page_token": "NQ==",
// "data": [
// {
// "id": 5,
// "amount": "25.0",
// "confirms": 100,
// "txid": "72e03037d144dae3d32b68b5045462b1049a0755",
// "is_internal": false,
// "inserted_at": "2018-02-16T11:39:58.000Z",
// "updated_at": "2018-11-09T10:20:09.000Z",
// "kind": "default",
// "memo": "",
// "state": "WITHHOLD",
// "asset_symbol": "BTS"
// }
// ]
// }
//
const deposits = this.safeValue (response, 'data', []);
return this.parseTransactions (deposits, code, since, limit);
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'page_token': 'dxzef', // request page after this page token
// 'limit': 50, // optional, default 50
// 'kind': 'string', // optional - air_drop, big_holder_dividend, default, eosc_to_eos, internal, equally_airdrop, referral_mining, one_holder_dividend, single_customer, snapshotted_airdrop, trade_mining
// 'asset_symbol': 'BTC', // optional
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['asset_symbol'] = currency['id'];
}
if (limit !== undefined) {
request['limit'] = limit; // default 50
}
const response = await this.privateGetWithdrawals (this.extend (request, params));
//
// {
// "code": 0,
// "data": [
// {
// "id": 10,
// "customer_id": "10",
// "asset_symbol": "ETH",
// "amount": "5",
// "state": "CONFIRMED",
// "note": "2018-03-15T16:13:45.610463Z",
// "txid": "0x4643bb6b393ac20a6175c713175734a72517c63d6f73a3ca90a15356f2e967da0",
// "completed_at": "2018-03-15T16:13:45.610463Z",
// "inserted_at": "2018-03-15T16:13:45.610463Z",
// "is_internal": true,
// "target_address": "0x4643bb6b393ac20a6175c713175734a72517c63d6f7"
// }
// ],
// "page_token":"dxvf"
// }
//
const withdrawals = this.safeValue (response, 'data', []);
return this.parseTransactions (withdrawals, code, since, limit);
}
async transfer (code, amount, fromAccount, toAccount, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const accountsByType = this.safeValue (this.options, 'accountsByType', {});
const accountsById = this.safeValue (this.options, 'accountsById', {});
const accountIds = Object.keys (accountsById);
const fromId = this.safeString (accountsByType, fromAccount, fromAccount);
if (!(fromId in accountIds)) {
throw new ExchangeError (this.id + ' transfer() fromAccount must be one of ' + accountIds.join (', '));
}
const toId = this.safeString (accountsByType, toAccount, toAccount);
if (!(toId in accountIds)) {
throw new ExchangeError (this.id + ' transfer() toAccount must be one of ' + accountIds.join (', '));
}
const type = this.safeString (params, 'type');
const subAccount = this.safeString (params, 'sub_account');
const guid = this.safeString (params, 'guid', this.uuid ());
const request = {
'symbol': currency['id'],
'amount': this.currencyToPrecision (code, amount),
'from': fromId,
'to': toId,
'guid': guid,
'type': type,
};
if (type !== undefined) {
request['type'] = type;
}
if (subAccount !== undefined) {
request['sub_account'] = subAccount;
}
const response = await this.privatePostTransfer (this.extend (request, params));
//
// {
// "code": 0,
// "data": null
// }
//
const transfer = this.parseTransfer (response, currency);
const transferOptions = this.safeValue (this.options, 'transfer', {});
const fillResponseFromRequest = this.safeValue (transferOptions, 'fillResponseFromRequest', true);
if (fillResponseFromRequest) {
transfer['fromAccount'] = fromAccount;
transfer['toAccount'] = toAccount;
transfer['amount'] = amount;
transfer['id'] = guid;
}
return transfer;
}
parseTransfer (transfer, currency = undefined) {
//
// {
// "code": 0,
// "data": null
// }
//
const code = this.safeNumber (transfer, 'code');
return {
'info': transfer,
'id': undefined,
'timestamp': undefined,
'datetime': undefined,
'currency': code,
'amount': undefined,
'fromAccount': undefined,
'toAccount': undefined,
'status': this.parseTransferStatus (code),
};
}
parseTransferStatus (status) {
const statuses = {
'0': 'ok',
};
return this.safeString (statuses, status, 'failed');
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
[ tag, params ] = this.handleWithdrawTagAndParams (tag, params);
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'symbol': currency['id'],
'target_address': address,
'amount': this.currencyToPrecision (code, amount),
};
if (tag !== undefined) {
request['memo'] = tag;
}
// requires write permission on the wallet
const response = await this.privatePostWithdrawals (this.extend (request, params));
//
// {
// "code":0,
// "message":"",
// "data":{
// "id":1077391,
// "customer_id":1082679,
// "amount":"21.9000000000000000",
// "txid":"",
// "is_internal":false,
// "kind":"on_chain",
// "state":"PENDING",
// "inserted_at":"2020-06-03T00:50:57+00:00",
// "updated_at":"2020-06-03T00:50:57+00:00",
// "memo":"",
// "target_address":"rDYtYT3dBeuw376rvHqoZBKW3UmvguoBAf",
// "fee":"0.1000000000000000",
// "asset_symbol":"XRP"
// }
// }
//
const data = this.safeValue (response, 'data', {});
return this.parseTransaction (data, currency);
}
handleErrors (httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) {
if (response === undefined) {
return; // fallback to default error handler
}
//
// {"code":10013,"message":"Resource not found"}
// {"code":40004,"message":"invalid jwt"}
//
const code = this.safeString (response, 'code');
const message = this.safeString (response, 'message');
if (code !== '0') {
const feedback = this.id + ' ' + body;
this.throwExactlyMatchedException (this.exceptions['exact'], message, feedback);
this.throwExactlyMatchedException (this.exceptions['exact'], code, feedback);
this.throwBroadlyMatchedException (this.exceptions['broad'], message, feedback);
throw new ExchangeError (feedback); // unknown message
}
}
};
| bigone transfer refix/cleanup | js/bigone.js | bigone transfer refix/cleanup | <ide><path>s/bigone.js
<ide> 'future': 'CONTRACT',
<ide> 'swap': 'CONTRACT',
<ide> },
<del> 'accountsById': {
<del> 'SPOT': 'spot',
<del> 'FUND': 'funding',
<del> 'CONTRACT': 'future',
<del> },
<ide> 'transfer': {
<ide> 'fillResponseFromRequest': true,
<ide> },
<ide> await this.loadMarkets ();
<ide> const currency = this.currency (code);
<ide> const accountsByType = this.safeValue (this.options, 'accountsByType', {});
<del> const accountsById = this.safeValue (this.options, 'accountsById', {});
<del> const accountIds = Object.keys (accountsById);
<ide> const fromId = this.safeString (accountsByType, fromAccount, fromAccount);
<del> if (!(fromId in accountIds)) {
<del> throw new ExchangeError (this.id + ' transfer() fromAccount must be one of ' + accountIds.join (', '));
<del> }
<ide> const toId = this.safeString (accountsByType, toAccount, toAccount);
<del> if (!(toId in accountIds)) {
<del> throw new ExchangeError (this.id + ' transfer() toAccount must be one of ' + accountIds.join (', '));
<del> }
<ide> const type = this.safeString (params, 'type');
<ide> const subAccount = this.safeString (params, 'sub_account');
<ide> const guid = this.safeString (params, 'guid', this.uuid ()); |
|
Java | apache-2.0 | 4deabde108e5433d81a80229e99194e3ec1af200 | 0 | hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity | package com.hubspot.singularity.scheduler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.rholder.retry.Retryer;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.hubspot.baragon.models.BaragonRequestState;
import com.hubspot.baragon.models.UpstreamInfo;
import com.hubspot.singularity.LoadBalancerRequestType;
import com.hubspot.singularity.LoadBalancerRequestType.LoadBalancerRequestId;
import com.hubspot.singularity.SingularityDeploy;
import com.hubspot.singularity.SingularityLoadBalancerUpdate;
import com.hubspot.singularity.SingularityRequest;
import com.hubspot.singularity.SingularityRequestWithState;
import com.hubspot.singularity.SingularityTask;
import com.hubspot.singularity.SingularityTaskId;
import com.hubspot.singularity.SingularityTaskIdsByStatus;
import com.hubspot.singularity.data.DeployManager;
import com.hubspot.singularity.data.RequestManager;
import com.hubspot.singularity.data.TaskManager;
import com.hubspot.singularity.helpers.RequestHelper;
import com.hubspot.singularity.hooks.LoadBalancerClient;
import com.hubspot.singularity.mesos.SingularitySchedulerLock;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.WaitStrategies;
@Singleton
public class SingularityUpstreamChecker {
private static final Logger LOG = LoggerFactory.getLogger(SingularityUpstreamChecker.class);
private static final Predicate<BaragonRequestState> IS_WAITING_STATE = baragonRequestState -> baragonRequestState == BaragonRequestState.WAITING;
private final LoadBalancerClient lbClient;
private final TaskManager taskManager;
private final RequestManager requestManager;
private final DeployManager deployManager;
private final RequestHelper requestHelper;
private final SingularitySchedulerLock lock;
@Inject
public SingularityUpstreamChecker(LoadBalancerClient lbClient,
TaskManager taskManager,
RequestManager requestManager,
DeployManager deployManager,
RequestHelper requestHelper,
SingularitySchedulerLock lock) {
this.lbClient = lbClient;
this.taskManager = taskManager;
this.requestManager = requestManager;
this.deployManager = deployManager;
this.requestHelper = requestHelper;
this.lock = lock;
}
private List<SingularityTask> getActiveHealthyTasksForRequest(String requestId) throws Exception {
final Optional<SingularityTaskIdsByStatus> taskIdsByStatusForRequest = requestHelper.getTaskIdsByStatusForRequest(requestId);
if (taskIdsByStatusForRequest.isPresent()) {
final List<SingularityTaskId> activeHealthyTaskIdsForRequest = taskIdsByStatusForRequest.get().getHealthy();
final Map<SingularityTaskId, SingularityTask> activeTasksForRequest = taskManager.getTasks(activeHealthyTaskIdsForRequest);
return new ArrayList<>(activeTasksForRequest.values());
}
LOG.error("TaskId not found for requestId: {}.", requestId);
throw new Exception("TaskId not found.");
}
private Collection<UpstreamInfo> getUpstreamsFromActiveTasksForRequest(String singularityRequestId, Optional<String> loadBalancerUpstreamGroup) throws Exception {
return lbClient.getUpstreamsForTasks(getActiveHealthyTasksForRequest(singularityRequestId), singularityRequestId, loadBalancerUpstreamGroup);
}
private boolean isEqualUpstreamGroupRackId(UpstreamInfo upstream1, UpstreamInfo upstream2){
return (upstream1.getUpstream().equals(upstream2.getUpstream()))
&& (upstream1.getGroup().equals(upstream2.getGroup()))
&& (upstream1.getRackId().equals(upstream2.getRackId()));
}
/**
* @param upstream
* @param upstreams
* @return a collection of upstreams in the upstreams param that match with the upstream param on upstream, group and rackId
* We expect that the collection will have a maximum of one match, but we will keep it as a collection just in case
*/
private Collection<UpstreamInfo> getEqualUpstreams(UpstreamInfo upstream, Collection<UpstreamInfo> upstreams) {
return upstreams.stream().filter(candidate -> isEqualUpstreamGroupRackId(candidate, upstream)).collect(Collectors.toList());
}
private List<UpstreamInfo> getExtraUpstreams(Collection<UpstreamInfo> upstreamsInBaragonForRequest, Collection<UpstreamInfo> upstreamsInSingularityForRequest) {
for (UpstreamInfo upstreamInSingularity : upstreamsInSingularityForRequest) {
final Collection<UpstreamInfo> matches = getEqualUpstreams(upstreamInSingularity, upstreamsInBaragonForRequest);
upstreamsInBaragonForRequest.removeAll(matches);
}
return new ArrayList<>(upstreamsInBaragonForRequest);
}
private SingularityLoadBalancerUpdate syncUpstreamsForService(SingularityRequest singularityRequest, SingularityDeploy deploy, Optional<String> loadBalancerUpstreamGroup) throws Exception {
final String singularityRequestId = singularityRequest.getId();
final LoadBalancerRequestId loadBalancerRequestId = new LoadBalancerRequestId(singularityRequestId, LoadBalancerRequestType.REMOVE, Optional.absent());
Collection<UpstreamInfo> upstreamsInBaragonForRequest = lbClient.getLoadBalancerUpstreamsForRequest(loadBalancerRequestId.toString());
Collection<UpstreamInfo> upstreamsInSingularityForRequest = getUpstreamsFromActiveTasksForRequest(singularityRequestId, loadBalancerUpstreamGroup);
final List<UpstreamInfo> extraUpstreams = getExtraUpstreams(upstreamsInBaragonForRequest, upstreamsInSingularityForRequest);
LOG.info("Making and sending load balancer request to remove {} extra upstreams.", extraUpstreams.size());
LOG.info("Upstreams removed are: {}", Arrays.toString(extraUpstreams.toArray()));
return lbClient.makeAndSendLoadBalancerRequest(loadBalancerRequestId, Collections.emptyList(), extraUpstreams, deploy, singularityRequest);
}
private boolean noPendingDeploy() {
return deployManager.getPendingDeploys().size() == 0;
}
public void doSyncUpstreamForService(SingularityRequest singularityRequest) {
if (singularityRequest.isLoadBalanced() && noPendingDeploy()) {
final String singularityRequestId = singularityRequest.getId();
LOG.info("Doing syncing of upstreams for service: {}.", singularityRequestId);
final Optional<String> maybeDeployId = deployManager.getInUseDeployId(singularityRequestId);
if (maybeDeployId.isPresent()) {
final String deployId = maybeDeployId.get();
final Optional<SingularityDeploy> maybeDeploy = deployManager.getDeploy(singularityRequestId, deployId);
if (maybeDeploy.isPresent()) {
final SingularityDeploy deploy = maybeDeploy.get();
final Optional<String> loadBalancerUpstreamGroup = deploy.getLoadBalancerUpstreamGroup();
final SingularityLoadBalancerUpdate syncUpstreamsUpdate;
try {
syncUpstreamsUpdate = syncUpstreamsForService(singularityRequest, deploy, loadBalancerUpstreamGroup);
final LoadBalancerRequestId loadBalancerRequestId = syncUpstreamsUpdate.getLoadBalancerRequestId();
checkSyncUpstreamsState(loadBalancerRequestId, singularityRequestId);
} catch (Exception e) {
LOG.error("message", e);
}
}
}
}
}
public void checkSyncUpstreamsState(LoadBalancerRequestId loadBalancerRequestId, String singularityRequestId) {
Retryer<BaragonRequestState> syncingRetryer = RetryerBuilder.<BaragonRequestState>newBuilder()
.retryIfException()
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
.retryIfResult(IS_WAITING_STATE)
.build();
try {
BaragonRequestState syncUpstreamsState = syncingRetryer.call(() -> lbClient.getState(loadBalancerRequestId).getLoadBalancerState());
if (syncUpstreamsState == BaragonRequestState.SUCCESS){
LOG.info("Syncing upstreams for singularity request {} is {}. Load balancer request id is {}.", singularityRequestId, syncUpstreamsState.name(), loadBalancerRequestId.toString());
} else {
LOG.error("Syncing upstreams for singularity request {} is {}. Load balancer request id is {}.", singularityRequestId, syncUpstreamsState.name(), loadBalancerRequestId.toString());
}
} catch (Exception e) {
LOG.error("message", e);
}
}
public void syncUpstreams() {
for (SingularityRequestWithState singularityRequestWithState: requestManager.getActiveRequests()){
final SingularityRequest singularityRequest = singularityRequestWithState.getRequest();
lock.runWithRequestLock(() -> doSyncUpstreamForService(singularityRequest), singularityRequest.getId(), getClass().getSimpleName());
}
}
}
| SingularityService/src/main/java/com/hubspot/singularity/scheduler/SingularityUpstreamChecker.java | package com.hubspot.singularity.scheduler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.rholder.retry.Retryer;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.hubspot.baragon.models.BaragonRequestState;
import com.hubspot.baragon.models.UpstreamInfo;
import com.hubspot.singularity.LoadBalancerRequestType;
import com.hubspot.singularity.LoadBalancerRequestType.LoadBalancerRequestId;
import com.hubspot.singularity.SingularityDeploy;
import com.hubspot.singularity.SingularityLoadBalancerUpdate;
import com.hubspot.singularity.SingularityRequest;
import com.hubspot.singularity.SingularityRequestWithState;
import com.hubspot.singularity.SingularityTask;
import com.hubspot.singularity.SingularityTaskId;
import com.hubspot.singularity.SingularityTaskIdsByStatus;
import com.hubspot.singularity.data.DeployManager;
import com.hubspot.singularity.data.RequestManager;
import com.hubspot.singularity.data.TaskManager;
import com.hubspot.singularity.helpers.RequestHelper;
import com.hubspot.singularity.hooks.LoadBalancerClient;
import com.hubspot.singularity.mesos.SingularitySchedulerLock;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.WaitStrategies;
@Singleton
public class SingularityUpstreamChecker {
private static final Logger LOG = LoggerFactory.getLogger(SingularityUpstreamChecker.class);
private final LoadBalancerClient lbClient;
private final TaskManager taskManager;
private final RequestManager requestManager;
private final DeployManager deployManager;
private final RequestHelper requestHelper;
private final SingularitySchedulerLock lock;
@Inject
public SingularityUpstreamChecker(LoadBalancerClient lbClient,
TaskManager taskManager,
RequestManager requestManager,
DeployManager deployManager,
RequestHelper requestHelper,
SingularitySchedulerLock lock) {
this.lbClient = lbClient;
this.taskManager = taskManager;
this.requestManager = requestManager;
this.deployManager = deployManager;
this.requestHelper = requestHelper;
this.lock = lock;
}
private List<SingularityTask> getActiveHealthyTasksForRequest(String requestId) throws Exception {
final Optional<SingularityTaskIdsByStatus> taskIdsByStatusForRequest = requestHelper.getTaskIdsByStatusForRequest(requestId);
if (taskIdsByStatusForRequest.isPresent()) {
final List<SingularityTaskId> activeHealthyTaskIdsForRequest = taskIdsByStatusForRequest.get().getHealthy();
final Map<SingularityTaskId, SingularityTask> activeTasksForRequest = taskManager.getTasks(activeHealthyTaskIdsForRequest);
return new ArrayList<>(activeTasksForRequest.values());
}
LOG.error("TaskId not found for requestId: {}.", requestId);
throw new Exception("TaskId not found.");
}
private Collection<UpstreamInfo> getUpstreamsFromActiveTasksForRequest(String singularityRequestId, Optional<String> loadBalancerUpstreamGroup) throws Exception {
return lbClient.getUpstreamsForTasks(getActiveHealthyTasksForRequest(singularityRequestId), singularityRequestId, loadBalancerUpstreamGroup);
}
private boolean isEqualUpstreamGroupRackId(UpstreamInfo upstream1, UpstreamInfo upstream2){
return (upstream1.getUpstream().equals(upstream2.getUpstream()))
&& (upstream1.getGroup().equals(upstream2.getGroup()))
&& (upstream1.getRackId().equals(upstream2.getRackId()));
}
/**
* @param upstream
* @param upstreams
* @return a collection of upstreams in the upstreams param that match with the upstream param on upstream, group and rackId
* We expect that the collection will have a maximum of one match, but we will keep it as a collection just in case
*/
private Collection<UpstreamInfo> getEqualUpstreams(UpstreamInfo upstream, Collection<UpstreamInfo> upstreams) {
return upstreams.stream().filter(candidate -> isEqualUpstreamGroupRackId(candidate, upstream)).collect(Collectors.toList());
}
private List<UpstreamInfo> getExtraUpstreams(Collection<UpstreamInfo> upstreamsInBaragonForRequest, Collection<UpstreamInfo> upstreamsInSingularityForRequest) {
for (UpstreamInfo upstreamInSingularity : upstreamsInSingularityForRequest) {
final Collection<UpstreamInfo> matches = getEqualUpstreams(upstreamInSingularity, upstreamsInBaragonForRequest);
upstreamsInBaragonForRequest.removeAll(matches);
}
return new ArrayList<>(upstreamsInBaragonForRequest);
}
private SingularityLoadBalancerUpdate syncUpstreamsForService(SingularityRequest singularityRequest, SingularityDeploy deploy, Optional<String> loadBalancerUpstreamGroup) throws Exception {
final String singularityRequestId = singularityRequest.getId();
final LoadBalancerRequestId loadBalancerRequestId = new LoadBalancerRequestId(singularityRequestId, LoadBalancerRequestType.REMOVE, Optional.absent());
Collection<UpstreamInfo> upstreamsInBaragonForRequest = lbClient.getLoadBalancerUpstreamsForRequest(loadBalancerRequestId.toString());
Collection<UpstreamInfo> upstreamsInSingularityForRequest = getUpstreamsFromActiveTasksForRequest(singularityRequestId, loadBalancerUpstreamGroup);
final List<UpstreamInfo> extraUpstreams = getExtraUpstreams(upstreamsInBaragonForRequest, upstreamsInSingularityForRequest);
LOG.info("Making and sending load balancer request to remove {} extra upstreams.", extraUpstreams.size());
LOG.info("Upstreams removed are: {}", Arrays.toString(extraUpstreams.toArray()));
return lbClient.makeAndSendLoadBalancerRequest(loadBalancerRequestId, Collections.emptyList(), extraUpstreams, deploy, singularityRequest);
}
private boolean noPendingDeploy() {
return deployManager.getPendingDeploys().size() == 0;
}
public void doSyncUpstreamForService(SingularityRequest singularityRequest) {
if (singularityRequest.isLoadBalanced() && noPendingDeploy()) {
final String singularityRequestId = singularityRequest.getId();
LOG.info("Doing syncing of upstreams for service: {}.", singularityRequestId);
final Optional<String> maybeDeployId = deployManager.getInUseDeployId(singularityRequestId);
if (maybeDeployId.isPresent()) {
final String deployId = maybeDeployId.get();
final Optional<SingularityDeploy> maybeDeploy = deployManager.getDeploy(singularityRequestId, deployId);
if (maybeDeploy.isPresent()) {
final SingularityDeploy deploy = maybeDeploy.get();
final Optional<String> loadBalancerUpstreamGroup = deploy.getLoadBalancerUpstreamGroup();
final SingularityLoadBalancerUpdate syncUpstreamsUpdate;
try {
syncUpstreamsUpdate = syncUpstreamsForService(singularityRequest, deploy, loadBalancerUpstreamGroup);
final LoadBalancerRequestId loadBalancerRequestId = syncUpstreamsUpdate.getLoadBalancerRequestId();
checkSyncUpstreamsState(loadBalancerRequestId, singularityRequestId);
} catch (Exception e) {
LOG.error("message", e);
}
}
}
}
}
private Predicate<BaragonRequestState> baragonRequestStateIsWaiting = baragonRequestState -> baragonRequestState == BaragonRequestState.WAITING;
public void checkSyncUpstreamsState(LoadBalancerRequestId loadBalancerRequestId, String singularityRequestId) {
Retryer<BaragonRequestState> syncingRetryer = RetryerBuilder.<BaragonRequestState>newBuilder()
.retryIfException()
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
.retryIfResult(baragonRequestStateIsWaiting)
.build();
try {
BaragonRequestState syncUpstreamsState = syncingRetryer.call(() -> lbClient.getState(loadBalancerRequestId).getLoadBalancerState());
if (syncUpstreamsState == BaragonRequestState.SUCCESS){
LOG.info("Syncing upstreams for singularity request {} is {}. Load balancer request id is {}.", singularityRequestId, syncUpstreamsState.name(), loadBalancerRequestId.toString());
} else {
LOG.error("Syncing upstreams for singularity request {} is {}. Load balancer request id is {}.", singularityRequestId, syncUpstreamsState.name(), loadBalancerRequestId.toString());
}
} catch (Exception e) {
LOG.error("message", e);
}
}
public void syncUpstreams() {
for (SingularityRequestWithState singularityRequestWithState: requestManager.getActiveRequests()){
final SingularityRequest singularityRequest = singularityRequestWithState.getRequest();
lock.runWithRequestLock(() -> doSyncUpstreamForService(singularityRequest), singularityRequest.getId(), getClass().getSimpleName());
}
}
}
| styling
| SingularityService/src/main/java/com/hubspot/singularity/scheduler/SingularityUpstreamChecker.java | styling | <ide><path>ingularityService/src/main/java/com/hubspot/singularity/scheduler/SingularityUpstreamChecker.java
<ide> public class SingularityUpstreamChecker {
<ide>
<ide> private static final Logger LOG = LoggerFactory.getLogger(SingularityUpstreamChecker.class);
<add> private static final Predicate<BaragonRequestState> IS_WAITING_STATE = baragonRequestState -> baragonRequestState == BaragonRequestState.WAITING;
<add>
<ide> private final LoadBalancerClient lbClient;
<ide> private final TaskManager taskManager;
<ide> private final RequestManager requestManager;
<ide> }
<ide> }
<ide>
<del> private Predicate<BaragonRequestState> baragonRequestStateIsWaiting = baragonRequestState -> baragonRequestState == BaragonRequestState.WAITING;
<del>
<ide> public void checkSyncUpstreamsState(LoadBalancerRequestId loadBalancerRequestId, String singularityRequestId) {
<ide> Retryer<BaragonRequestState> syncingRetryer = RetryerBuilder.<BaragonRequestState>newBuilder()
<ide> .retryIfException()
<ide> .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
<del> .retryIfResult(baragonRequestStateIsWaiting)
<add> .retryIfResult(IS_WAITING_STATE)
<ide> .build();
<ide> try {
<ide> BaragonRequestState syncUpstreamsState = syncingRetryer.call(() -> lbClient.getState(loadBalancerRequestId).getLoadBalancerState()); |
|
Java | apache-2.0 | 90be47d264359f2c2b7e744d9d73e1d2c1ef72c8 | 0 | winhamwr/selenium,virajs/selenium-1,virajs/selenium-1,virajs/selenium-1,virajs/selenium-1,winhamwr/selenium,winhamwr/selenium,winhamwr/selenium,virajs/selenium-1,virajs/selenium-1,virajs/selenium-1,winhamwr/selenium,winhamwr/selenium,virajs/selenium-1,winhamwr/selenium,virajs/selenium-1,winhamwr/selenium | /*
Copyright 2010 WebDriver committers
Copyright 2010 Google 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 org.openqa.selenium.net;
import org.openqa.selenium.Platform;
import java.io.IOException;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.SECONDS;
@SuppressWarnings({"UtilityClass"})
public class PortProber {
private static final Random random = new Random();
private static final EphemeralPortRangeDetector ephemeralRangeDetector;
static {
final Platform current = Platform.getCurrent();
if (current.is(Platform.LINUX)) {
ephemeralRangeDetector = LinuxEphemeralPortRangeDetector.getInstance();
} else if (current.is(Platform.XP)){
ephemeralRangeDetector = new OlderWindowsVersionEphemeralPortDetector();
} else {
ephemeralRangeDetector = new FixedIANAPortRange();
}
}
public static int findFreePort() {
for (int i = 0; i < 5; i++) {
int seedPort = createAcceptablePort();
int suggestedPort = checkPortIsFree(seedPort);
if (suggestedPort != -1) {
return suggestedPort;
}
}
throw new RuntimeException("Unable to find a free port");
}
public static Callable<Integer> freeLocalPort(final int port) {
return new Callable<Integer>() {
public Integer call()
throws Exception {
if (checkPortIsFree(port) != -1) {
return port;
}
return null;
}
};
}
/**
* Returns a port that is within a probable free range. <p/> Based on the ports in
* http://en.wikipedia.org/wiki/Ephemeral_ports, this method stays away from all well-known
* ephemeral port ranges, since they can arbitrarily race with the operating system in
* allocations. Due to the port-greedy nature of selenium this happens fairly frequently.
* Staying within the known safe range increases the probability tests will run green quite
* significantly.
*
* @return a random port number
*/
private static int createAcceptablePort() {
synchronized (random) {
final int FIRST_PORT;
final int LAST_PORT;
if (ephemeralRangeDetector.getHighestEphemeralPort() < 32768){
FIRST_PORT = ephemeralRangeDetector.getHighestEphemeralPort() + 1;
LAST_PORT = 65535;
} else {
FIRST_PORT = 1024;
LAST_PORT = ephemeralRangeDetector.getLowestEphemeralPort() - 1;
}
if (FIRST_PORT == LAST_PORT) {
return FIRST_PORT;
}
final int randomInt = random.nextInt();
final int portWithoutOffset = Math.abs(randomInt % (LAST_PORT - FIRST_PORT + 1));
return portWithoutOffset + FIRST_PORT;
}
}
private static int checkPortIsFree(int port) {
ServerSocket socket;
try {
socket = new ServerSocket(port);
int localPort = socket.getLocalPort();
socket.close();
return localPort;
} catch (IOException e) {
return -1;
}
}
public static boolean pollPort(int port) {
return pollPort(port, 15, SECONDS);
}
public static boolean pollPort(int port, int timeout, TimeUnit unit) {
long end = System.currentTimeMillis() + unit.toMillis(timeout);
while (System.currentTimeMillis() < end) {
try {
Socket socket = new Socket("localhost", port);
socket.close();
return true;
} catch (ConnectException e) {
// Ignore this
} catch (UnknownHostException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return false;
}
}
| java/client/src/org/openqa/selenium/net/PortProber.java | /*
Copyright 2010 WebDriver committers
Copyright 2010 Google 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 org.openqa.selenium.net;
import org.openqa.selenium.Platform;
import java.io.IOException;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.SECONDS;
@SuppressWarnings({"UtilityClass"})
public class PortProber {
private static final Random random = new Random();
private static final EphemeralPortRangeDetector ephemeralRangeDetector;
static {
final Platform current = Platform.getCurrent();
if (current.is(Platform.LINUX)) {
ephemeralRangeDetector = LinuxEphemeralPortRangeDetector.getInstance();
} else if (current.is(Platform.XP)){
ephemeralRangeDetector = new OlderWindowsVersionEphemeralPortDetector();
} else {
ephemeralRangeDetector = new FixedIANAPortRange();
}
}
public static int findFreePort() {
for (int i = 0; i < 5; i++) {
int seedPort = createAcceptablePort();
int suggestedPort = checkPortIsFree(seedPort);
if (suggestedPort != -1) {
return suggestedPort;
}
}
throw new RuntimeException("Unable to find a free port");
}
public static Callable<Integer> freeLocalPort(final int port) {
return new Callable<Integer>() {
public Integer call()
throws Exception {
if (checkPortIsFree(port) != -1) {
return port;
}
return null;
}
};
}
/**
* Returns a port that is within a probable free range. <p/> Based on the ports in
* http://en.wikipedia.org/wiki/Ephemeral_ports, this method stays away from all well-known
* ephemeral port ranges, since they can arbitrarily race with the operating system in
* allocations. Due to the port-greedy nature of selenium this happens fairly frequently.
* Staying within the known safe range increases the probability tests will run green quite
* significantly.
*
* @return a random port number
*/
private static int createAcceptablePort() {
synchronized (random) {
final int FIRST_PORT;
final int LAST_PORT;
if (ephemeralRangeDetector.getHighestEphemeralPort() < 32768){
FIRST_PORT = ephemeralRangeDetector.getHighestEphemeralPort() + 1;
LAST_PORT = 65535;
} else {
FIRST_PORT = 1024;
LAST_PORT = ephemeralRangeDetector.getLowestEphemeralPort() - 1;
}
final int randomInt = random.nextInt();
final int portWithoutOffset = Math.abs(randomInt % (LAST_PORT - FIRST_PORT + 1));
return portWithoutOffset + FIRST_PORT;
}
}
private static int checkPortIsFree(int port) {
ServerSocket socket;
try {
socket = new ServerSocket(port);
int localPort = socket.getLocalPort();
socket.close();
return localPort;
} catch (IOException e) {
return -1;
}
}
public static boolean pollPort(int port) {
return pollPort(port, 15, SECONDS);
}
public static boolean pollPort(int port, int timeout, TimeUnit unit) {
long end = System.currentTimeMillis() + unit.toMillis(timeout);
while (System.currentTimeMillis() < end) {
try {
Socket socket = new Socket("localhost", port);
socket.close();
return true;
} catch (ConnectException e) {
// Ignore this
} catch (UnknownHostException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return false;
}
}
| DanielWagnerHall: Eliminating divide by zero bug. Fixes issue 2646.
git-svn-id: 4179480af2c2519a5eb5e1e9b541cbdf5cf27696@14113 07704840-8298-11de-bf8c-fd130f914ac9
| java/client/src/org/openqa/selenium/net/PortProber.java | DanielWagnerHall: Eliminating divide by zero bug. Fixes issue 2646. | <ide><path>ava/client/src/org/openqa/selenium/net/PortProber.java
<ide> FIRST_PORT = 1024;
<ide> LAST_PORT = ephemeralRangeDetector.getLowestEphemeralPort() - 1;
<ide> }
<add> if (FIRST_PORT == LAST_PORT) {
<add> return FIRST_PORT;
<add> }
<ide> final int randomInt = random.nextInt();
<ide> final int portWithoutOffset = Math.abs(randomInt % (LAST_PORT - FIRST_PORT + 1));
<ide> return portWithoutOffset + FIRST_PORT; |
|
Java | apache-2.0 | 94b0b8231707313dff68f62bf245799e0c7ffc28 | 0 | alainsahli/confluence-publisher,alainsahli/confluence-publisher,alainsahli/confluence-publisher,alainsahli/confluence-publisher | /*
* Copyright 2016-2017 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.sahli.asciidoc.confluence.publisher.converter;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.sahli.asciidoc.confluence.publisher.converter.AsciidocPagesStructureProvider.AsciidocPage;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.copy;
import static java.nio.file.Files.createDirectories;
import static java.nio.file.Files.exists;
import static java.nio.file.Files.walk;
import static java.nio.file.Files.write;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static java.util.Collections.emptyList;
import static org.apache.commons.codec.digest.DigestUtils.sha256Hex;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.rules.ExpectedException.none;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sahli.asciidoc.confluence.publisher.converter.AsciidocConfluencePage.newAsciidocConfluencePage;
/**
* @author Alain Sahli
* @author Christian Stettler
*/
public class AsciidocConfluencePageTest {
private static final Path TEMPLATES_FOLDER = Paths.get("src/main/resources/org/sahli/asciidoc/confluence/publisher/converter/templates");
@ClassRule
public static final TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder();
@Rule
public final ExpectedException expectedException = none();
@Test
public void render_asciidocWithTopLevelHeader_returnsConfluencePageWithPageTitleFromTopLevelHeader() {
// arrange
String adoc = "= Page title";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(adoc), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciiDocConfluencePage.pageTitle(), is("Page title"));
}
@Test
public void render_asciidocWithTitleMetaInformation_returnsConfluencePageWithPageTitleFromTitleMetaInformation() {
// arrange
String adoc = "= Page title";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(adoc), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciiDocConfluencePage.pageTitle(), is("Page title"));
}
@Test
public void render_asciidocWithTopLevelHeaderAndMetaInformation_returnsConfluencePageWithPageTitleFromTitleMetaInformation() {
// arrange
String adoc = ":title: Page title (meta)\n" +
"= Page Title (header)";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(adoc), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciiDocConfluencePage.pageTitle(), is("Page title (meta)"));
}
@Test
public void render_asciidocWithTopLevelHeaderAndMetaInformationAndPageTitlePostProcessorConfigured_returnsConfluencePageWithPostProcessedPageTitleFromTitleMetaInformation() {
// arrange
String adoc = ":title: Page title (meta)\n" +
"= Page Title (header)";
PageTitlePostProcessor pageTitlePostProcessor = mock(PageTitlePostProcessor.class);
when(pageTitlePostProcessor.process("Page title (meta)")).thenReturn("Post-Processed Page Title");
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(adoc), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath(), pageTitlePostProcessor);
// assert
assertThat(asciidocConfluencePage.pageTitle(), is("Post-Processed Page Title"));
}
@Test
public void render_asciidocWithPageTitleAndPageTitlePostProcessorConfigured_returnsConfluencePageWithPostProcessedPageTitle() {
// arrange
String adoc = "= Page Title";
PageTitlePostProcessor pageTitlePostProcessor = mock(PageTitlePostProcessor.class);
when(pageTitlePostProcessor.process("Page Title")).thenReturn("Post-Processed Page Title");
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(adoc), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath(), pageTitlePostProcessor);
// assert
assertThat(asciidocConfluencePage.pageTitle(), is("Post-Processed Page Title"));
}
@Test
public void render_asciidocWithNeitherTopLevelHeaderNorTitleMetaInformation_returnsConfluencePageWithPageTitleFromMetaInformation() {
// arrange
String adoc = "Content";
// assert
this.expectedException.expect(RuntimeException.class);
this.expectedException.expectMessage("top-level heading or title meta information must be set");
// act
newAsciidocConfluencePage(asciidocPage(adoc), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
}
@Test
public void renderConfluencePage_asciiDocWithListing_returnsConfluencePageContentWithMacroWithNameNoFormat() {
// arrange
String adocContent = "----\n" +
"import java.util.List;\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"noformat\">" +
"<ac:plain-text-body><![CDATA[import java.util.List;]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithListingAndTitle_returnsConfluencePageContentWithMacroWithNameNoFormatAndTitle() {
// arrange
String adocContent = ".A block title\n" +
"----\n" +
"import java.util.List;\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"noformat\">" +
"<ac:parameter ac:name=\"title\">A block title</ac:parameter>" +
"<ac:plain-text-body><![CDATA[import java.util.List;]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithSourceListing_returnsConfluencePageContentWithMacroWithNameCode() {
// arrange
String adocContent = "[source]\n" +
"----\n" +
"import java.util.List;\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"code\">" +
"<ac:plain-text-body><![CDATA[import java.util.List;]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithJavaSourceListing_returnsConfluencePageContentWithMacroWithNameCodeAndParameterJava() {
// arrange
String adocContent = "[source,java]\n" +
"----\n" +
"import java.util.List;\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"code\">" +
"<ac:parameter ac:name=\"language\">java</ac:parameter>" +
"<ac:plain-text-body><![CDATA[import java.util.List;]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithSourceListingOfUnsupportedLanguage_returnsConfluencePageContentWithMacroWithoutLanguageElement() {
// arrange
String adocContent = "[source,unsupported]\n" +
"----\n" +
"GET /events?param1=value1¶m2=value2 HTTP/1.1\n" +
"Host: localhost:8080\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"code\">" +
"<ac:plain-text-body>" +
"<![CDATA[GET /events?param1=value1¶m2=value2 HTTP/1.1\nHost: localhost:8080]]>" +
"</ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithListingWithHtmlMarkup_returnsConfluencePageContentWithMacroWithoutHtmlEscape() {
// arrange
String adocContent = "----\n" +
"<b>line one</b>\n" +
"<b>line two</b>\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"noformat\">" +
"<ac:plain-text-body><![CDATA[<b>line one</b>\n<b>line two</b>]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithSourceListingWithHtmlContent_returnsConfluencePageContentWithoutHtmlEscape() {
// arrange
String adocContent = "[source]\n" +
"----\n" +
"<b>content with html</b>\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"code\">" +
"<ac:plain-text-body><![CDATA[<b>content with html</b>]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithSourceListingWithRegularExpressionSymbols_returnsConfluencePageContentWithRegularExpressionSymbolsEscaped() {
// arrange
String adocContent = "[source]\n" +
"----\n" +
"[0-9][0-9]\\.[0-9][0-9]\\.[0-9]{4}$\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"code\">" +
"<ac:plain-text-body><![CDATA[[0-9][0-9]\\.[0-9][0-9]\\.[0-9]{4}$]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithAllPossibleSectionLevels_returnsConfluencePageContentWithAllSectionHavingCorrectMarkup() {
// arrange
String adocContent = "= Title level 0\n\n" +
"== Title level 1\n" +
"=== Title level 2\n" +
"==== Title level 3\n" +
"===== Title level 4\n" +
"====== Title level 5";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<h1>Title level 1</h1>" +
"<h2>Title level 2</h2>" +
"<h3>Title level 3</h3>" +
"<h4>Title level 4</h4>" +
"<h5>Title level 5</h5>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithParagraph_returnsConfluencePageContentHavingCorrectParagraphMarkup() {
// arrange
String adoc = "some paragraph";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adoc)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p>some paragraph</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithBoldText_returnsConfluencePageContentWithBoldMarkup() {
// arrange
String adocContent = "*Bold phrase.* bold le**t**ter.";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><strong>Bold phrase.</strong> bold le<strong>t</strong>ter.</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithBr_returnsConfluencePageContentWithXhtml() {
// arrange
String adocContent = "a +\nb +\nc";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p>a<br/>\nb<br/>\nc</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithItalicText_returnsConfluencePageContentWithItalicMarkup() {
// arrange
String adocContent = "_Italic phrase_ italic le__t__ter.";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><em>Italic phrase</em> italic le<em>t</em>ter.</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImageWithHeightAndWidthAttributeSurroundedByLink_returnsConfluencePageContentWithImageWithHeightAttributeMacroWrappedInLink() {
// arrange
String adocContent = "image::sunset.jpg[Sunset, 300, 200, link=\"http://www.foo.ch\"]";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<a href=\"http://www.foo.ch\"><ac:image ac:height=\"200\" ac:width=\"300\"><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image></a>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImageWithTitle_returnsConfluencePageContentWithImageWithTitle() {
String adocContent = ".A beautiful sunset\n" +
"image::sunset.jpg[]";
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
String expectedContent = "<ac:image ac:title=\"A beautiful sunset\" ac:alt=\"A beautiful sunset\"><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image><div class=\"cp-image-title\"><em>Figure 1. A beautiful sunset</em></div>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImage_returnsConfluencePageContentWithImage() {
// arrange
String adocContent = "image::sunset.jpg[]";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:image><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImageInDifferentFolder_returnsConfluencePageContentWithImageAttachmentFileNameOnly() {
// arrange
String adocContent = "image::sub-folder/sunset.jpg[]";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:image><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithoutTableWithHeader_returnsConfluencePageContentWithTableWithoutHeader() {
// arrange
String adocContent = "" +
"[cols=\"3*\"]\n" +
"|===\n" +
"| A\n" +
"| B\n" +
"| C\n" +
"\n" +
"| 10\n" +
"| 11\n" +
"| 12\n" +
"\n" +
"| 20\n" +
"| 21\n" +
"| 22\n" +
"|===";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<table><tbody><tr><td>A</td><td>B</td><td>C</td></tr><tr><td>10</td><td>11</td><td>12</td></tr><tr><td>20</td><td>21</td><td>22</td></tr></tbody></table>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithTableWithHeader_returnsConfluencePageContentWithTableWithHeader() {
// arrange
String adocContent = "" +
"[cols=\"3*\", options=\"header\"]\n" +
"|===\n" +
"| A\n" +
"| B\n" +
"| C\n" +
"\n" +
"| 10\n" +
"| 11\n" +
"| 12\n" +
"\n" +
"| 20\n" +
"| 21\n" +
"| 22\n" +
"|===";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<table><thead><tr><th>A</th><th>B</th><th>C</th></tr></thead><tbody><tr><td>10</td><td>11</td><td>12</td></tr><tr><td>20</td><td>21</td><td>22</td></tr></tbody></table>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithTableWithRowSpan_returnsConfluencePageWithTableWithRowSpan() {
// arrange
String adocContent = "" +
"[cols=\"3*\", options=\"header\"]\n" +
"|===\n" +
"| A\n" +
"| B\n" +
"| C\n" +
"\n" +
".2+| 10\n" +
"| 11\n" +
"| 12\n" +
"| 13\n" +
"| 14\n" +
"|===";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
String expectedContent = "<table><thead><tr><th>A</th><th>B</th><th>C</th></tr></thead><tbody><tr><td rowspan=\"2\">10</td><td>11</td><td>12</td></tr><tr><td>13</td><td>14</td></tr></tbody></table>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithTableWithColSpan_returnsConfluencePageWithTableWithColSpan() {
// arrange
String adocContent = "" +
"[cols=\"3*\", options=\"header\"]\n" +
"|===\n" +
"| A\n" +
"| B\n" +
"| C\n" +
"\n" +
"| 10\n" +
"2+| 11 & 12\n" +
"\n" +
"|===";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
String expectedContent = "<table><thead><tr><th>A</th><th>B</th><th>C</th></tr></thead><tbody><tr><td>10</td><td colspan=\"2\">11 & 12</td></tr></tbody></table>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithTableWithAsciiDocCell_returnsConfluencePageWithTableWithAsciiDocCell() {
// arrange
String adocContent = "" +
"|===\n" +
"| A " +
"| B\n" +
"\n" +
"| 10 " +
"a|11\n" +
"\n" +
"* 12 \n" +
"* 13 \n" +
"\n" +
"|===";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
String expectedContent = "<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody><tr><td>10</td><td><div><p>11</p>\n<ul><li>12</li><li>13</li></ul></div></td></tr></tbody></table>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithNoteContent_returnsConfluencePageContentWithInfoMacroWithContent() {
// arrange
String adocContent = "[NOTE]\n" +
"====\n" +
"Some note.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"info\">" +
"<ac:rich-text-body><p>Some note.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithNoteContentAndTitle_returnsConfluencePageContentWithInfoMacroWithContentAndTitle() {
// arrange
String adocContent = "[NOTE]\n" +
".Note Title\n" +
"====\n" +
"Some note.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"info\">" +
"<ac:parameter ac:name=\"title\">Note Title</ac:parameter>" +
"<ac:rich-text-body><p>Some note.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithTipContent_returnsConfluencePageContentWithTipMacroWithContent() {
// arrange
String adocContent = "[TIP]\n" +
"====\n" +
"Some tip.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"tip\">" +
"<ac:rich-text-body><p>Some tip.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithTipContentAndTitle_returnsConfluencePageContentWithTipMacroWithContentAndTitle() {
// arrange
String adocContent = "[TIP]\n" +
".Tip Title\n" +
"====\n" +
"Some tip.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"tip\">" +
"<ac:parameter ac:name=\"title\">Tip Title</ac:parameter>" +
"<ac:rich-text-body><p>Some tip.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithCautionContent_returnsConfluencePageContentWithNoteMacroWithContent() {
// arrange
String adocContent = "[CAUTION]\n" +
"====\n" +
"Some caution.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"note\">" +
"<ac:rich-text-body><p>Some caution.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithCautionContentAndTitle_returnsConfluencePageContentWithNoteMacroWithContentAndTitle() {
// arrange
String adocContent = "[CAUTION]\n" +
".Caution Title\n" +
"====\n" +
"Some caution.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"note\">" +
"<ac:parameter ac:name=\"title\">Caution Title</ac:parameter>" +
"<ac:rich-text-body><p>Some caution.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithWarningContent_returnsConfluencePageContentWithNoteMacroWithContent() {
// arrange
String adocContent = "[WARNING]\n" +
"====\n" +
"Some warning.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"note\">" +
"<ac:rich-text-body><p>Some warning.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithWarningContentAndTitle_returnsConfluencePageContentWithNoteMacroWithContentAndTitle() {
// arrange
String adocContent = "[WARNING]\n" +
".Warning Title\n" +
"====\n" +
"Some warning.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"note\">" +
"<ac:parameter ac:name=\"title\">Warning Title</ac:parameter>" +
"<ac:rich-text-body><p>Some warning.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImportantContent_returnsConfluencePageContentWithNoteMacroWithContent() {
// arrange
String adocContent = "[IMPORTANT]\n" +
"====\n" +
"Some important.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"warning\">" +
"<ac:rich-text-body><p>Some important.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImportantContentAndTitle_returnsConfluencePageContentWithNoteMacroWithContentAndTitle() {
// arrange
String adocContent = "[IMPORTANT]\n" +
".Important Title\n" +
"====\n" +
"Some important.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"warning\">" +
"<ac:parameter ac:name=\"title\">Important Title</ac:parameter>" +
"<ac:rich-text-body><p>Some important.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInterDocumentCrossReference_returnsConfluencePageWithLinkToReferencedPageByPageTitle() {
// arrange
Path rootFolder = copyAsciidocSourceToTemporaryFolder("src/test/resources/inter-document-cross-references");
AsciidocPage asciidocPage = asciidocPage(rootFolder, "source-page.adoc");
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
String expectedContent = "<p>This is a <ac:link><ri:page ri:content-title=\"Target Page\"></ri:page>" +
"<ac:plain-text-link-body><![CDATA[reference]]></ac:plain-text-link-body>" +
"</ac:link> to the target page.</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithCircularInterDocumentCrossReference_returnsConfluencePagesWithLinkToReferencedPageByPageTitle() {
// arrange
AsciidocPage asciidocPageOne = asciidocPage(Paths.get("src/test/resources/circular-inter-document-cross-references/page-one.adoc"));
AsciidocPage asciidocPageTwo = asciidocPage(Paths.get("src/test/resources/circular-inter-document-cross-references/page-two.adoc"));
// act
AsciidocConfluencePage asciidocConfluencePageOne = newAsciidocConfluencePage(asciidocPageOne, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPageOne));
AsciidocConfluencePage asciidocConfluencePageTwo = newAsciidocConfluencePage(asciidocPageTwo, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPageTwo));
// assert
assertThat(asciidocConfluencePageOne.content(), containsString("<ri:page ri:content-title=\"Page Two\">"));
assertThat(asciidocConfluencePageTwo.content(), containsString("<ri:page ri:content-title=\"Page One\">"));
}
@Test
public void renderConfluencePage_asciiDocWithLinkToAttachmentWithoutLinkText_returnsConfluencePageWithLinkToAttachmentAndAttachmentNameAsLinkText() {
// arrange
String adocContent = "link:foo.txt[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><ac:link><ri:attachment ri:filename=\"foo.txt\"></ri:attachment></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithLinkToAttachmentWithLinkText_returnsConfluencePageWithLinkToAttachmentAndSpecifiedLinkText() {
// arrange
String adocContent = "link:foo.txt[Bar]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><ac:link><ri:attachment ri:filename=\"foo.txt\"></ri:attachment><ac:plain-text-link-body><![CDATA[Bar]]></ac:plain-text-link-body></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInclude_returnsConfluencePageWithContentFromIncludedPage() {
// arrange
Path rootFolder = copyAsciidocSourceToTemporaryFolder("src/test/resources/includes");
AsciidocPage asciidocPage = asciidocPage(rootFolder, "page.adoc");
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
assertThat(asciidocConfluencePage.content(), containsString("<p>main content</p>"));
assertThat(asciidocConfluencePage.content(), containsString("<p>included content</p>"));
}
@Test
public void renderConfluencePage_asciiDocWithUtf8CharacterInTitle_returnsConfluencePageWithCorrectlyEncodedUtf8CharacterInTitle() {
try {
// arrange
setDefaultCharset(ISO_8859_1);
String adocContent = "= Title © !";
AsciidocPage asciidocPage = asciidocPage(adocContent);
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
assertThat(asciidocConfluencePage.pageTitle(), is("Title © !"));
} finally {
setDefaultCharset(UTF_8);
}
}
@Test
public void renderConfluencePage_asciiDocWithUtf8CharacterInContent_returnsConfluencePageWithCorrectlyEncodedUtf8CharacterInContent() {
try {
// arrange
setDefaultCharset(ISO_8859_1);
String adocContent = "Copyrighted content © !";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
assertThat(asciidocConfluencePage.content(), is("<p>Copyrighted content © !</p>"));
} finally {
setDefaultCharset(UTF_8);
}
}
@Test
public void renderConfluencePage_asciiDocWithIsoEncodingAndSpecificSourceEncodingConfigured_returnsConfluencePageWithCorrectlyEncodedContent() {
// arrange
AsciidocPage asciidocPage = asciidocPage(Paths.get("src/test/resources/encoding/iso-encoded-source.adoc"));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, ISO_8859_1, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
assertThat(asciidocConfluencePage.content(), is("<p>This line contains an ISO-8859-1 encoded special character 'À'.</p>"));
}
@Test
public void renderConfluencePage_asciiDocWithLinkToAttachmentInDifferentFolder_returnsConfluencePageWithLinkToAttachmentFileNameOnly() {
// arrange
String adocContent = "link:bar/foo.txt[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><ac:link><ri:attachment ri:filename=\"foo.txt\"></ri:attachment></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithExplicitExternalLinkAndLinkText_returnsConfluencePageWithLinkToExternalPageAndSpecifiedLinkText() {
// arrange
String adocContent = "link:http://www.google.com[Google]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><a href=\"http://www.google.com\">Google</a></p>";
assertThat(asciidocConfluencePage.content(), containsString(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithExternalLinkWithoutLinkText_returnsConfluencePageWithLinkToExternalPageAndUrlAsLinkText() {
// arrange
String adocContent = "link:http://www.google.com[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><a href=\"http://www.google.com\">http://www.google.com</a></p>";
assertThat(asciidocConfluencePage.content(), containsString(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImplicitExternalLink_returnsConfluencePageWithLinkToExternalPageAndUrlAsLinkText() {
// arrange
String adocContent = "http://www.google.com";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><a href=\"http://www.google.com\">http://www.google.com</a></p>";
assertThat(asciidocConfluencePage.content(), containsString(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithEmbeddedPlantUmlDiagram_returnsConfluencePageWithLinkToGeneratedPlantUmlImage() {
// arrange
String adocContent = "[plantuml, embedded-diagram, png]\n" +
"....\n" +
"A <|-- B\n" +
"....";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
String expectedContent = "<ac:image ac:height=\"175\" ac:width=\"57\"><ri:attachment ri:filename=\"embedded-diagram.png\"></ri:attachment></ac:image>";
assertThat(asciidocConfluencePage.content(), containsString(expectedContent));
assertThat(exists(assetsTargetFolderFor(asciidocPage).resolve("embedded-diagram.png")), is(true));
}
@Test
public void renderConfluencePage_asciiDocWithIncludedPlantUmlFile_returnsConfluencePageWithLinkToGeneratedPlantUmlImage() {
// arrange
Path rootFolder = copyAsciidocSourceToTemporaryFolder("src/test/resources/plantuml");
AsciidocPage asciidocPage = asciidocPage(rootFolder, "page.adoc");
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
String expectedContent = "<ac:image ac:height=\"175\" ac:width=\"57\"><ri:attachment ri:filename=\"included-diagram.png\"></ri:attachment></ac:image>";
assertThat(asciidocConfluencePage.content(), containsString(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithUnorderedList_returnsConfluencePageHavingCorrectUnorderedListMarkup() {
// arrange
String adocContent = "* L1-1\n" +
"** L2-1\n" +
"*** L3-1\n" +
"**** L4-1\n" +
"***** L5-1\n" +
"* L1-2";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ul><li>L1-1<ul><li>L2-1<ul><li>L3-1<ul><li>L4-1<ul><li>L5-1</li></ul></li></ul></li></ul></li></ul></li><li>L1-2</li></ul>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithUnorderedListAndTitle_returnsConfluencePageHavingCorrectUnorderedListAndTitleMarkup() {
// arrange
String adocContent = ".An unordered list title\n" +
"* L1-1\n" +
"* L1-2\n";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<div class=\"cp-ulist-title\"><em>An unordered list title</em></div>" + "<ul><li>L1-1</li><li>L1-2</li></ul>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithOrderedList_returnsConfluencePageHavingCorrectOrderedListMarkup() {
// arrange
String adocContent = ". L1-1\n" +
".. L2-1\n" +
"... L3-1\n" +
".... L4-1\n" +
"..... L5-1\n" +
". L1-2";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ol><li>L1-1<ol><li>L2-1<ol><li>L3-1<ol><li>L4-1<ol><li>L5-1</li></ol></li></ol></li></ol></li></ol></li><li>L1-2</li></ol>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithOrderedListAndTitle_returnsConfluencePageHavingCorrectOrderedListAndTitleMarkup() {
// arrange
String adocContent = ".An ordered list title\n" +
". L1-1\n" +
". L1-2\n";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<div class=\"cp-olist-title\"><em>An ordered list title</em></div>" +
"<ol><li>L1-1</li><li>L1-2</li></ol>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInlineImage_returnsConfluencePageWithInlineImage() {
// arrange
String adocContent = "Some text image:sunset.jpg[] with inline image";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p>Some text <ac:image ac:alt=\"sunset\"><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image> with inline image</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInlineImageWithHeightAndWidthAttributeSurroundedByLink_returnsConfluencePageContentWithInlineImageWithHeightAttributeMacroWrappedInLink() {
// arrange
String adocContent = "Some text image:sunset.jpg[Sunset, 16, 20, link=\"http://www.foo.ch\"] with inline image";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p>Some text <a href=\"http://www.foo.ch\"><ac:image ac:height=\"20\" ac:width=\"16\" ac:alt=\"Sunset\"><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image></a> with inline image</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInlineImageInDifferentFolder_returnsConfluencePageContentWithInlineImageAttachmentFileNameOnly() {
// arrange
String adocContent = "Some text image:sub-folder/sunset.jpg[] with inline image";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p>Some text <ac:image ac:alt=\"sunset\"><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image> with inline image</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInternalCrossReferenceToSection_returnsConfluencePageContentWithInternalCrossReferenceToSectionUsingSectionTitle() {
// arrange
String adocContent = "" +
"== Section 1 [[section1]]\n" +
"Cross reference to <<section1>>";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "" +
"<h1>Section 1</h1>" +
"<p>Cross reference to <ac:link ac:anchor=\"section1\"><ac:plain-text-link-body><![CDATA[Section 1]]></ac:plain-text-link-body></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInternalCrossReferenceToSectionAndCustomLabel_returnsConfluencePageContentWithInternalCrossReferenceToSectionUsingCustomLabel() {
// arrange
String adocContent = "" +
"== Section 1 [[section1]]\n" +
"Cross reference to <<section1,section 1>>";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "" +
"<h1>Section 1</h1>" +
"<p>Cross reference to <ac:link ac:anchor=\"section1\"><ac:plain-text-link-body><![CDATA[section 1]]></ac:plain-text-link-body></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInternalCrossReferenceToParagraph_returnsConfluencePageContentWithInternalCrossReferenceToParagraphUsingAnchorId() {
// arrange
String adocContent = "" +
"[[paragraph1]]Paragraph\n\n" +
"Cross reference to <<paragraph1>>";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "" +
"<p><ac:structured-macro ac:name=\"anchor\"><ac:parameter ac:name=\"\">paragraph1</ac:parameter></ac:structured-macro>Paragraph</p>\n" +
"<p>Cross reference to <ac:link ac:anchor=\"paragraph1\"><ac:plain-text-link-body><![CDATA[[paragraph1]]]></ac:plain-text-link-body></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInternalCrossReferenceToParagraphAndCustomLabel_returnsConfluencePageContentWithInternalCrossReferenceToParagraphUsingCustomLabel() {
// arrange
String adocContent = "" +
"[[paragraph1]]Paragraph\n\n" +
"Cross reference to <<paragraph1,Paragraph>>";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "" +
"<p><ac:structured-macro ac:name=\"anchor\"><ac:parameter ac:name=\"\">paragraph1</ac:parameter></ac:structured-macro>Paragraph</p>\n" +
"<p>Cross reference to <ac:link ac:anchor=\"paragraph1\"><ac:plain-text-link-body><![CDATA[Paragraph]]></ac:plain-text-link-body></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void attachments_asciiDocWithImage_returnsImageAsAttachmentWithPathAndName() {
// arrange
String adocContent = "image::sunset.jpg[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(1));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sunset.jpg", "sunset.jpg"));
}
@Test
public void attachments_asciiDocWithImageInDifferentFolder_returnsImageAsAttachmentWithPathAndFileNameOnly() {
// arrange
String adocContent = "image::sub-folder/sunset.jpg[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(1));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sub-folder/sunset.jpg", "sunset.jpg"));
}
@Test
public void attachments_asciiDocWithMultipleLevelsAndImages_returnsAllAttachments() {
// arrange
String adocContent = "= Title 1\n\n" +
"image::sunset.jpg[]\n" +
"== Title 2\n" +
"image::sunrise.jpg[]";
AsciidocPage asciidocPage = asciidocPage(adocContent);
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(2));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sunset.jpg", "sunset.jpg"));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sunrise.jpg", "sunrise.jpg"));
}
@Test
public void attachments_asciiDocWithMultipleTimesSameImage_returnsNoDuplicateAttachments() {
// arrange
String adocContent = "image::sunrise.jpg[]\n" +
"image::sunrise.jpg[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(1));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sunrise.jpg", "sunrise.jpg"));
}
@Test
public void attachments_asciiDocWithLinkToAttachment_returnsAttachmentWithPathAndName() {
// arrange
String adocContent = "link:foo.txt[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(1));
assertThat(asciidocConfluencePage.attachments(), hasEntry("foo.txt", "foo.txt"));
}
@Test
public void attachments_asciiDocWithLinkToAttachmentInDifferentFolder_returnsAttachmentWithPathAndFileNameOnly() {
// arrange
String adocContent = "link:sub-folder/foo.txt[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(1));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sub-folder/foo.txt", "foo.txt"));
}
@Test
public void attachments_asciiDocWithImageAndLinkToAttachment_returnsAllAttachments() {
// arrange
String adocContent = "image::sunrise.jpg[]\n" +
"link:foo.txt[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(2));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sunrise.jpg", "sunrise.jpg"));
assertThat(asciidocConfluencePage.attachments(), hasEntry("foo.txt", "foo.txt"));
}
private static String prependTitle(String content) {
if (!content.startsWith("= ")) {
content = "= Default Page Title\n\n" + content;
}
return content;
}
private static Path assetsTargetFolderFor(AsciidocPage asciidocPage) {
return asciidocPage.path().getParent();
}
private static Path dummyAssetsTargetPath() {
try {
return TEMPORARY_FOLDER.newFolder().toPath();
} catch (IOException e) {
throw new RuntimeException("Could not create assert target path", e);
}
}
private static Path copyAsciidocSourceToTemporaryFolder(String pathToSampleAsciidocStructure) {
try {
Path sourceFolder = Paths.get(pathToSampleAsciidocStructure);
Path targetFolder = TEMPORARY_FOLDER.newFolder().toPath();
walk(Paths.get(pathToSampleAsciidocStructure)).forEach((path) -> copyTo(path, targetFolder.resolve(sourceFolder.relativize(path))));
return targetFolder;
} catch (IOException e) {
throw new RuntimeException("Could not copy sample asciidoc structure", e);
}
}
private static void copyTo(Path sourcePath, Path targetPath) {
try {
createDirectories(targetPath.getParent());
copy(sourcePath, targetPath, REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException("Could not copy source path to target path", e);
}
}
private static Path temporaryPath(String content) {
try {
Path path = TEMPORARY_FOLDER.newFolder().toPath().resolve("tmp").resolve(sha256Hex(content) + ".adoc");
createDirectories(path.getParent());
write(path, content.getBytes(UTF_8));
return path;
} catch (IOException e) {
throw new RuntimeException("Could not write content to temporary path", e);
}
}
private AsciidocPage asciidocPage(Path rootFolder, String asciidocFileName) {
return asciidocPage(rootFolder.resolve(asciidocFileName));
}
private AsciidocPage asciidocPage(Path contentPath) {
return new TestAsciidocPage(contentPath);
}
private AsciidocPage asciidocPage(String content) {
return asciidocPage(temporaryPath(content));
}
private static class TestAsciidocPage implements AsciidocPage {
private final Path path;
TestAsciidocPage(Path path) {
this.path = path;
}
@Override
public Path path() {
return this.path;
}
@Override
public List<AsciidocPage> children() {
return emptyList();
}
}
private static void setDefaultCharset(Charset charset) {
try {
Field defaultCharsetField = Charset.class.getDeclaredField("defaultCharset");
defaultCharsetField.setAccessible(true);
defaultCharsetField.set(null, charset);
} catch (Exception e) {
throw new RuntimeException("Could not set default charset", e);
}
}
}
| asciidoc-confluence-publisher-converter/src/test/java/org/sahli/asciidoc/confluence/publisher/converter/AsciidocConfluencePageTest.java | /*
* Copyright 2016-2017 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.sahli.asciidoc.confluence.publisher.converter;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.sahli.asciidoc.confluence.publisher.converter.AsciidocPagesStructureProvider.AsciidocPage;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.copy;
import static java.nio.file.Files.createDirectories;
import static java.nio.file.Files.exists;
import static java.nio.file.Files.walk;
import static java.nio.file.Files.write;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static java.util.Collections.emptyList;
import static org.apache.commons.codec.digest.DigestUtils.sha256Hex;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.rules.ExpectedException.none;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sahli.asciidoc.confluence.publisher.converter.AsciidocConfluencePage.newAsciidocConfluencePage;
/**
* @author Alain Sahli
* @author Christian Stettler
*/
public class AsciidocConfluencePageTest {
private static final Path TEMPLATES_FOLDER = Paths.get("src/main/resources/org/sahli/asciidoc/confluence/publisher/converter/templates");
@ClassRule
public static final TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder();
@Rule
public final ExpectedException expectedException = none();
@Test
public void render_asciidocWithTopLevelHeader_returnsConfluencePageWithPageTitleFromTopLevelHeader() {
// arrange
String adoc = "= Page title";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(adoc), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciiDocConfluencePage.pageTitle(), is("Page title"));
}
@Test
public void render_asciidocWithTitleMetaInformation_returnsConfluencePageWithPageTitleFromTitleMetaInformation() {
// arrange
String adoc = "= Page title";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(adoc), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciiDocConfluencePage.pageTitle(), is("Page title"));
}
@Test
public void render_asciidocWithTopLevelHeaderAndMetaInformation_returnsConfluencePageWithPageTitleFromTitleMetaInformation() {
// arrange
String adoc = ":title: Page title (meta)\n" +
"= Page Title (header)";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(adoc), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciiDocConfluencePage.pageTitle(), is("Page title (meta)"));
}
@Test
public void render_asciidocWithTopLevelHeaderAndMetaInformationAndPageTitlePostProcessorConfigured_returnsConfluencePageWithPostProcessedPageTitleFromTitleMetaInformation() {
// arrange
String adoc = ":title: Page title (meta)\n" +
"= Page Title (header)";
PageTitlePostProcessor pageTitlePostProcessor = mock(PageTitlePostProcessor.class);
when(pageTitlePostProcessor.process("Page title (meta)")).thenReturn("Post-Processed Page Title");
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(adoc), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath(), pageTitlePostProcessor);
// assert
assertThat(asciidocConfluencePage.pageTitle(), is("Post-Processed Page Title"));
}
@Test
public void render_asciidocWithPageTitleAndPageTitlePostProcessorConfigured_returnsConfluencePageWithPostProcessedPageTitle() {
// arrange
String adoc = "= Page Title";
PageTitlePostProcessor pageTitlePostProcessor = mock(PageTitlePostProcessor.class);
when(pageTitlePostProcessor.process("Page Title")).thenReturn("Post-Processed Page Title");
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(adoc), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath(), pageTitlePostProcessor);
// assert
assertThat(asciidocConfluencePage.pageTitle(), is("Post-Processed Page Title"));
}
@Test
public void render_asciidocWithNeitherTopLevelHeaderNorTitleMetaInformation_returnsConfluencePageWithPageTitleFromMetaInformation() {
// arrange
String adoc = "Content";
// assert
this.expectedException.expect(RuntimeException.class);
this.expectedException.expectMessage("top-level heading or title meta information must be set");
// act
newAsciidocConfluencePage(asciidocPage(adoc), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
}
@Test
public void renderConfluencePage_asciiDocWithListing_returnsConfluencePageContentWithMacroWithNameNoFormat() {
// arrange
String adocContent = "----\n" +
"import java.util.List;\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"noformat\">" +
"<ac:plain-text-body><![CDATA[import java.util.List;]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithSourceListing_returnsConfluencePageContentWithMacroWithNameCode() {
// arrange
String adocContent = "[source]\n" +
"----\n" +
"import java.util.List;\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"code\">" +
"<ac:plain-text-body><![CDATA[import java.util.List;]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithJavaSourceListing_returnsConfluencePageContentWithMacroWithNameCodeAndParameterJava() {
// arrange
String adocContent = "[source,java]\n" +
"----\n" +
"import java.util.List;\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"code\">" +
"<ac:parameter ac:name=\"language\">java</ac:parameter>" +
"<ac:plain-text-body><![CDATA[import java.util.List;]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithSourceListingOfUnsupportedLanguage_returnsConfluencePageContentWithMacroWithoutLanguageElement() {
// arrange
String adocContent = "[source,unsupported]\n" +
"----\n" +
"GET /events?param1=value1¶m2=value2 HTTP/1.1\n" +
"Host: localhost:8080\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"code\">" +
"<ac:plain-text-body>" +
"<![CDATA[GET /events?param1=value1¶m2=value2 HTTP/1.1\nHost: localhost:8080]]>" +
"</ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithListingWithHtmlMarkup_returnsConfluencePageContentWithMacroWithoutHtmlEscape() {
// arrange
String adocContent = "----\n" +
"<b>line one</b>\n" +
"<b>line two</b>\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"noformat\">" +
"<ac:plain-text-body><![CDATA[<b>line one</b>\n<b>line two</b>]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithSourceListingWithHtmlContent_returnsConfluencePageContentWithoutHtmlEscape() {
// arrange
String adocContent = "[source]\n" +
"----\n" +
"<b>content with html</b>\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"code\">" +
"<ac:plain-text-body><![CDATA[<b>content with html</b>]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithSourceListingWithRegularExpressionSymbols_returnsConfluencePageContentWithRegularExpressionSymbolsEscaped() {
// arrange
String adocContent = "[source]\n" +
"----\n" +
"[0-9][0-9]\\.[0-9][0-9]\\.[0-9]{4}$\n" +
"----";
// act
AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"code\">" +
"<ac:plain-text-body><![CDATA[[0-9][0-9]\\.[0-9][0-9]\\.[0-9]{4}$]]></ac:plain-text-body>" +
"</ac:structured-macro>";
assertThat(asciiDocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithAllPossibleSectionLevels_returnsConfluencePageContentWithAllSectionHavingCorrectMarkup() {
// arrange
String adocContent = "= Title level 0\n\n" +
"== Title level 1\n" +
"=== Title level 2\n" +
"==== Title level 3\n" +
"===== Title level 4\n" +
"====== Title level 5";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<h1>Title level 1</h1>" +
"<h2>Title level 2</h2>" +
"<h3>Title level 3</h3>" +
"<h4>Title level 4</h4>" +
"<h5>Title level 5</h5>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithParagraph_returnsConfluencePageContentHavingCorrectParagraphMarkup() {
// arrange
String adoc = "some paragraph";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adoc)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p>some paragraph</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithBoldText_returnsConfluencePageContentWithBoldMarkup() {
// arrange
String adocContent = "*Bold phrase.* bold le**t**ter.";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><strong>Bold phrase.</strong> bold le<strong>t</strong>ter.</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithBr_returnsConfluencePageContentWithXhtml() {
// arrange
String adocContent = "a +\nb +\nc";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p>a<br/>\nb<br/>\nc</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithItalicText_returnsConfluencePageContentWithItalicMarkup() {
// arrange
String adocContent = "_Italic phrase_ italic le__t__ter.";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><em>Italic phrase</em> italic le<em>t</em>ter.</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImageWithHeightAndWidthAttributeSurroundedByLink_returnsConfluencePageContentWithImageWithHeightAttributeMacroWrappedInLink() {
// arrange
String adocContent = "image::sunset.jpg[Sunset, 300, 200, link=\"http://www.foo.ch\"]";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<a href=\"http://www.foo.ch\"><ac:image ac:height=\"200\" ac:width=\"300\"><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image></a>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImage_returnsConfluencePageContentWithImage() {
// arrange
String adocContent = "image::sunset.jpg[]";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:image><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImageInDifferentFolder_returnsConfluencePageContentWithImageAttachmentFileNameOnly() {
// arrange
String adocContent = "image::sub-folder/sunset.jpg[]";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:image><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithoutTableWithHeader_returnsConfluencePageContentWithTableWithoutHeader() {
// arrange
String adocContent = "" +
"[cols=\"3*\"]\n" +
"|===\n" +
"| A\n" +
"| B\n" +
"| C\n" +
"\n" +
"| 10\n" +
"| 11\n" +
"| 12\n" +
"\n" +
"| 20\n" +
"| 21\n" +
"| 22\n" +
"|===";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<table><tbody><tr><td>A</td><td>B</td><td>C</td></tr><tr><td>10</td><td>11</td><td>12</td></tr><tr><td>20</td><td>21</td><td>22</td></tr></tbody></table>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithTableWithHeader_returnsConfluencePageContentWithTableWithHeader() {
// arrange
String adocContent = "" +
"[cols=\"3*\", options=\"header\"]\n" +
"|===\n" +
"| A\n" +
"| B\n" +
"| C\n" +
"\n" +
"| 10\n" +
"| 11\n" +
"| 12\n" +
"\n" +
"| 20\n" +
"| 21\n" +
"| 22\n" +
"|===";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<table><thead><tr><th>A</th><th>B</th><th>C</th></tr></thead><tbody><tr><td>10</td><td>11</td><td>12</td></tr><tr><td>20</td><td>21</td><td>22</td></tr></tbody></table>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithTableWithRowSpan_returnsConfluencePageWithTableWithRowSpan() {
// arrange
String adocContent = "" +
"[cols=\"3*\", options=\"header\"]\n" +
"|===\n" +
"| A\n" +
"| B\n" +
"| C\n" +
"\n" +
".2+| 10\n" +
"| 11\n" +
"| 12\n" +
"| 13\n" +
"| 14\n" +
"|===";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
String expectedContent = "<table><thead><tr><th>A</th><th>B</th><th>C</th></tr></thead><tbody><tr><td rowspan=\"2\">10</td><td>11</td><td>12</td></tr><tr><td>13</td><td>14</td></tr></tbody></table>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithTableWithColSpan_returnsConfluencePageWithTableWithColSpan() {
// arrange
String adocContent = "" +
"[cols=\"3*\", options=\"header\"]\n" +
"|===\n" +
"| A\n" +
"| B\n" +
"| C\n" +
"\n" +
"| 10\n" +
"2+| 11 & 12\n" +
"\n" +
"|===";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
String expectedContent = "<table><thead><tr><th>A</th><th>B</th><th>C</th></tr></thead><tbody><tr><td>10</td><td colspan=\"2\">11 & 12</td></tr></tbody></table>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithTableWithAsciiDocCell_returnsConfluencePageWithTableWithAsciiDocCell() {
// arrange
String adocContent = "" +
"|===\n" +
"| A " +
"| B\n" +
"\n" +
"| 10 " +
"a|11\n" +
"\n" +
"* 12 \n" +
"* 13 \n" +
"\n" +
"|===";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
String expectedContent = "<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody><tr><td>10</td><td><div><p>11</p>\n<ul><li>12</li><li>13</li></ul></div></td></tr></tbody></table>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithNoteContent_returnsConfluencePageContentWithInfoMacroWithContent() {
// arrange
String adocContent = "[NOTE]\n" +
"====\n" +
"Some note.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"info\">" +
"<ac:rich-text-body><p>Some note.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithNoteContentAndTitle_returnsConfluencePageContentWithInfoMacroWithContentAndTitle() {
// arrange
String adocContent = "[NOTE]\n" +
".Note Title\n" +
"====\n" +
"Some note.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"info\">" +
"<ac:parameter ac:name=\"title\">Note Title</ac:parameter>" +
"<ac:rich-text-body><p>Some note.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithTipContent_returnsConfluencePageContentWithTipMacroWithContent() {
// arrange
String adocContent = "[TIP]\n" +
"====\n" +
"Some tip.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"tip\">" +
"<ac:rich-text-body><p>Some tip.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithTipContentAndTitle_returnsConfluencePageContentWithTipMacroWithContentAndTitle() {
// arrange
String adocContent = "[TIP]\n" +
".Tip Title\n" +
"====\n" +
"Some tip.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"tip\">" +
"<ac:parameter ac:name=\"title\">Tip Title</ac:parameter>" +
"<ac:rich-text-body><p>Some tip.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithCautionContent_returnsConfluencePageContentWithNoteMacroWithContent() {
// arrange
String adocContent = "[CAUTION]\n" +
"====\n" +
"Some caution.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"note\">" +
"<ac:rich-text-body><p>Some caution.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithCautionContentAndTitle_returnsConfluencePageContentWithNoteMacroWithContentAndTitle() {
// arrange
String adocContent = "[CAUTION]\n" +
".Caution Title\n" +
"====\n" +
"Some caution.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"note\">" +
"<ac:parameter ac:name=\"title\">Caution Title</ac:parameter>" +
"<ac:rich-text-body><p>Some caution.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithWarningContent_returnsConfluencePageContentWithNoteMacroWithContent() {
// arrange
String adocContent = "[WARNING]\n" +
"====\n" +
"Some warning.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"note\">" +
"<ac:rich-text-body><p>Some warning.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithWarningContentAndTitle_returnsConfluencePageContentWithNoteMacroWithContentAndTitle() {
// arrange
String adocContent = "[WARNING]\n" +
".Warning Title\n" +
"====\n" +
"Some warning.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"note\">" +
"<ac:parameter ac:name=\"title\">Warning Title</ac:parameter>" +
"<ac:rich-text-body><p>Some warning.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImportantContent_returnsConfluencePageContentWithNoteMacroWithContent() {
// arrange
String adocContent = "[IMPORTANT]\n" +
"====\n" +
"Some important.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"warning\">" +
"<ac:rich-text-body><p>Some important.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImportantContentAndTitle_returnsConfluencePageContentWithNoteMacroWithContentAndTitle() {
// arrange
String adocContent = "[IMPORTANT]\n" +
".Important Title\n" +
"====\n" +
"Some important.\n" +
"====";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ac:structured-macro ac:name=\"warning\">" +
"<ac:parameter ac:name=\"title\">Important Title</ac:parameter>" +
"<ac:rich-text-body><p>Some important.</p></ac:rich-text-body>" +
"</ac:structured-macro>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInterDocumentCrossReference_returnsConfluencePageWithLinkToReferencedPageByPageTitle() {
// arrange
Path rootFolder = copyAsciidocSourceToTemporaryFolder("src/test/resources/inter-document-cross-references");
AsciidocPage asciidocPage = asciidocPage(rootFolder, "source-page.adoc");
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
String expectedContent = "<p>This is a <ac:link><ri:page ri:content-title=\"Target Page\"></ri:page>" +
"<ac:plain-text-link-body><![CDATA[reference]]></ac:plain-text-link-body>" +
"</ac:link> to the target page.</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithCircularInterDocumentCrossReference_returnsConfluencePagesWithLinkToReferencedPageByPageTitle() {
// arrange
AsciidocPage asciidocPageOne = asciidocPage(Paths.get("src/test/resources/circular-inter-document-cross-references/page-one.adoc"));
AsciidocPage asciidocPageTwo = asciidocPage(Paths.get("src/test/resources/circular-inter-document-cross-references/page-two.adoc"));
// act
AsciidocConfluencePage asciidocConfluencePageOne = newAsciidocConfluencePage(asciidocPageOne, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPageOne));
AsciidocConfluencePage asciidocConfluencePageTwo = newAsciidocConfluencePage(asciidocPageTwo, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPageTwo));
// assert
assertThat(asciidocConfluencePageOne.content(), containsString("<ri:page ri:content-title=\"Page Two\">"));
assertThat(asciidocConfluencePageTwo.content(), containsString("<ri:page ri:content-title=\"Page One\">"));
}
@Test
public void renderConfluencePage_asciiDocWithLinkToAttachmentWithoutLinkText_returnsConfluencePageWithLinkToAttachmentAndAttachmentNameAsLinkText() {
// arrange
String adocContent = "link:foo.txt[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><ac:link><ri:attachment ri:filename=\"foo.txt\"></ri:attachment></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithLinkToAttachmentWithLinkText_returnsConfluencePageWithLinkToAttachmentAndSpecifiedLinkText() {
// arrange
String adocContent = "link:foo.txt[Bar]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><ac:link><ri:attachment ri:filename=\"foo.txt\"></ri:attachment><ac:plain-text-link-body><![CDATA[Bar]]></ac:plain-text-link-body></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInclude_returnsConfluencePageWithContentFromIncludedPage() {
// arrange
Path rootFolder = copyAsciidocSourceToTemporaryFolder("src/test/resources/includes");
AsciidocPage asciidocPage = asciidocPage(rootFolder, "page.adoc");
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
assertThat(asciidocConfluencePage.content(), containsString("<p>main content</p>"));
assertThat(asciidocConfluencePage.content(), containsString("<p>included content</p>"));
}
@Test
public void renderConfluencePage_asciiDocWithUtf8CharacterInTitle_returnsConfluencePageWithCorrectlyEncodedUtf8CharacterInTitle() {
try {
// arrange
setDefaultCharset(ISO_8859_1);
String adocContent = "= Title © !";
AsciidocPage asciidocPage = asciidocPage(adocContent);
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
assertThat(asciidocConfluencePage.pageTitle(), is("Title © !"));
} finally {
setDefaultCharset(UTF_8);
}
}
@Test
public void renderConfluencePage_asciiDocWithUtf8CharacterInContent_returnsConfluencePageWithCorrectlyEncodedUtf8CharacterInContent() {
try {
// arrange
setDefaultCharset(ISO_8859_1);
String adocContent = "Copyrighted content © !";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
assertThat(asciidocConfluencePage.content(), is("<p>Copyrighted content © !</p>"));
} finally {
setDefaultCharset(UTF_8);
}
}
@Test
public void renderConfluencePage_asciiDocWithIsoEncodingAndSpecificSourceEncodingConfigured_returnsConfluencePageWithCorrectlyEncodedContent() {
// arrange
AsciidocPage asciidocPage = asciidocPage(Paths.get("src/test/resources/encoding/iso-encoded-source.adoc"));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, ISO_8859_1, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
assertThat(asciidocConfluencePage.content(), is("<p>This line contains an ISO-8859-1 encoded special character 'À'.</p>"));
}
@Test
public void renderConfluencePage_asciiDocWithLinkToAttachmentInDifferentFolder_returnsConfluencePageWithLinkToAttachmentFileNameOnly() {
// arrange
String adocContent = "link:bar/foo.txt[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><ac:link><ri:attachment ri:filename=\"foo.txt\"></ri:attachment></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithExplicitExternalLinkAndLinkText_returnsConfluencePageWithLinkToExternalPageAndSpecifiedLinkText() {
// arrange
String adocContent = "link:http://www.google.com[Google]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><a href=\"http://www.google.com\">Google</a></p>";
assertThat(asciidocConfluencePage.content(), containsString(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithExternalLinkWithoutLinkText_returnsConfluencePageWithLinkToExternalPageAndUrlAsLinkText() {
// arrange
String adocContent = "link:http://www.google.com[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><a href=\"http://www.google.com\">http://www.google.com</a></p>";
assertThat(asciidocConfluencePage.content(), containsString(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithImplicitExternalLink_returnsConfluencePageWithLinkToExternalPageAndUrlAsLinkText() {
// arrange
String adocContent = "http://www.google.com";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p><a href=\"http://www.google.com\">http://www.google.com</a></p>";
assertThat(asciidocConfluencePage.content(), containsString(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithEmbeddedPlantUmlDiagram_returnsConfluencePageWithLinkToGeneratedPlantUmlImage() {
// arrange
String adocContent = "[plantuml, embedded-diagram, png]\n" +
"....\n" +
"A <|-- B\n" +
"....";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
String expectedContent = "<ac:image ac:height=\"175\" ac:width=\"57\"><ri:attachment ri:filename=\"embedded-diagram.png\"></ri:attachment></ac:image>";
assertThat(asciidocConfluencePage.content(), containsString(expectedContent));
assertThat(exists(assetsTargetFolderFor(asciidocPage).resolve("embedded-diagram.png")), is(true));
}
@Test
public void renderConfluencePage_asciiDocWithIncludedPlantUmlFile_returnsConfluencePageWithLinkToGeneratedPlantUmlImage() {
// arrange
Path rootFolder = copyAsciidocSourceToTemporaryFolder("src/test/resources/plantuml");
AsciidocPage asciidocPage = asciidocPage(rootFolder, "page.adoc");
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, assetsTargetFolderFor(asciidocPage));
// assert
String expectedContent = "<ac:image ac:height=\"175\" ac:width=\"57\"><ri:attachment ri:filename=\"included-diagram.png\"></ri:attachment></ac:image>";
assertThat(asciidocConfluencePage.content(), containsString(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithUnorderedList_returnsConfluencePageHavingCorrectUnorderedListMarkup() {
// arrange
String adocContent = "* L1-1\n" +
"** L2-1\n" +
"*** L3-1\n" +
"**** L4-1\n" +
"***** L5-1\n" +
"* L1-2";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ul><li>L1-1<ul><li>L2-1<ul><li>L3-1<ul><li>L4-1<ul><li>L5-1</li></ul></li></ul></li></ul></li></ul></li><li>L1-2</li></ul>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithOrderedList_returnsConfluencePageHavingCorrectOrderedListMarkup() {
// arrange
String adocContent = ". L1-1\n" +
".. L2-1\n" +
"... L3-1\n" +
".... L4-1\n" +
"..... L5-1\n" +
". L1-2";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<ol><li>L1-1<ol><li>L2-1<ol><li>L3-1<ol><li>L4-1<ol><li>L5-1</li></ol></li></ol></li></ol></li></ol></li><li>L1-2</li></ol>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInlineImage_returnsConfluencePageWithInlineImage() {
// arrange
String adocContent = "Some text image:sunset.jpg[] with inline image";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p>Some text <ac:image ac:alt=\"sunset\"><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image> with inline image</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInlineImageWithHeightAndWidthAttributeSurroundedByLink_returnsConfluencePageContentWithInlineImageWithHeightAttributeMacroWrappedInLink() {
// arrange
String adocContent = "Some text image:sunset.jpg[Sunset, 16, 20, link=\"http://www.foo.ch\"] with inline image";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p>Some text <a href=\"http://www.foo.ch\"><ac:image ac:height=\"20\" ac:width=\"16\" ac:alt=\"Sunset\"><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image></a> with inline image</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInlineImageInDifferentFolder_returnsConfluencePageContentWithInlineImageAttachmentFileNameOnly() {
// arrange
String adocContent = "Some text image:sub-folder/sunset.jpg[] with inline image";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "<p>Some text <ac:image ac:alt=\"sunset\"><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image> with inline image</p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInternalCrossReferenceToSection_returnsConfluencePageContentWithInternalCrossReferenceToSectionUsingSectionTitle() {
// arrange
String adocContent = "" +
"== Section 1 [[section1]]\n" +
"Cross reference to <<section1>>";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "" +
"<h1>Section 1</h1>" +
"<p>Cross reference to <ac:link ac:anchor=\"section1\"><ac:plain-text-link-body><![CDATA[Section 1]]></ac:plain-text-link-body></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInternalCrossReferenceToSectionAndCustomLabel_returnsConfluencePageContentWithInternalCrossReferenceToSectionUsingCustomLabel() {
// arrange
String adocContent = "" +
"== Section 1 [[section1]]\n" +
"Cross reference to <<section1,section 1>>";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "" +
"<h1>Section 1</h1>" +
"<p>Cross reference to <ac:link ac:anchor=\"section1\"><ac:plain-text-link-body><![CDATA[section 1]]></ac:plain-text-link-body></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInternalCrossReferenceToParagraph_returnsConfluencePageContentWithInternalCrossReferenceToParagraphUsingAnchorId() {
// arrange
String adocContent = "" +
"[[paragraph1]]Paragraph\n\n" +
"Cross reference to <<paragraph1>>";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "" +
"<p><ac:structured-macro ac:name=\"anchor\"><ac:parameter ac:name=\"\">paragraph1</ac:parameter></ac:structured-macro>Paragraph</p>\n" +
"<p>Cross reference to <ac:link ac:anchor=\"paragraph1\"><ac:plain-text-link-body><![CDATA[[paragraph1]]]></ac:plain-text-link-body></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void renderConfluencePage_asciiDocWithInternalCrossReferenceToParagraphAndCustomLabel_returnsConfluencePageContentWithInternalCrossReferenceToParagraphUsingCustomLabel() {
// arrange
String adocContent = "" +
"[[paragraph1]]Paragraph\n\n" +
"Cross reference to <<paragraph1,Paragraph>>";
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
String expectedContent = "" +
"<p><ac:structured-macro ac:name=\"anchor\"><ac:parameter ac:name=\"\">paragraph1</ac:parameter></ac:structured-macro>Paragraph</p>\n" +
"<p>Cross reference to <ac:link ac:anchor=\"paragraph1\"><ac:plain-text-link-body><![CDATA[Paragraph]]></ac:plain-text-link-body></ac:link></p>";
assertThat(asciidocConfluencePage.content(), is(expectedContent));
}
@Test
public void attachments_asciiDocWithImage_returnsImageAsAttachmentWithPathAndName() {
// arrange
String adocContent = "image::sunset.jpg[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(1));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sunset.jpg", "sunset.jpg"));
}
@Test
public void attachments_asciiDocWithImageInDifferentFolder_returnsImageAsAttachmentWithPathAndFileNameOnly() {
// arrange
String adocContent = "image::sub-folder/sunset.jpg[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(1));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sub-folder/sunset.jpg", "sunset.jpg"));
}
@Test
public void attachments_asciiDocWithMultipleLevelsAndImages_returnsAllAttachments() {
// arrange
String adocContent = "= Title 1\n\n" +
"image::sunset.jpg[]\n" +
"== Title 2\n" +
"image::sunrise.jpg[]";
AsciidocPage asciidocPage = asciidocPage(adocContent);
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(2));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sunset.jpg", "sunset.jpg"));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sunrise.jpg", "sunrise.jpg"));
}
@Test
public void attachments_asciiDocWithMultipleTimesSameImage_returnsNoDuplicateAttachments() {
// arrange
String adocContent = "image::sunrise.jpg[]\n" +
"image::sunrise.jpg[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(1));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sunrise.jpg", "sunrise.jpg"));
}
@Test
public void attachments_asciiDocWithLinkToAttachment_returnsAttachmentWithPathAndName() {
// arrange
String adocContent = "link:foo.txt[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(1));
assertThat(asciidocConfluencePage.attachments(), hasEntry("foo.txt", "foo.txt"));
}
@Test
public void attachments_asciiDocWithLinkToAttachmentInDifferentFolder_returnsAttachmentWithPathAndFileNameOnly() {
// arrange
String adocContent = "link:sub-folder/foo.txt[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(1));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sub-folder/foo.txt", "foo.txt"));
}
@Test
public void attachments_asciiDocWithImageAndLinkToAttachment_returnsAllAttachments() {
// arrange
String adocContent = "image::sunrise.jpg[]\n" +
"link:foo.txt[]";
AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
// act
AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
// assert
assertThat(asciidocConfluencePage.attachments().size(), is(2));
assertThat(asciidocConfluencePage.attachments(), hasEntry("sunrise.jpg", "sunrise.jpg"));
assertThat(asciidocConfluencePage.attachments(), hasEntry("foo.txt", "foo.txt"));
}
private static String prependTitle(String content) {
if (!content.startsWith("= ")) {
content = "= Default Page Title\n\n" + content;
}
return content;
}
private static Path assetsTargetFolderFor(AsciidocPage asciidocPage) {
return asciidocPage.path().getParent();
}
private static Path dummyAssetsTargetPath() {
try {
return TEMPORARY_FOLDER.newFolder().toPath();
} catch (IOException e) {
throw new RuntimeException("Could not create assert target path", e);
}
}
private static Path copyAsciidocSourceToTemporaryFolder(String pathToSampleAsciidocStructure) {
try {
Path sourceFolder = Paths.get(pathToSampleAsciidocStructure);
Path targetFolder = TEMPORARY_FOLDER.newFolder().toPath();
walk(Paths.get(pathToSampleAsciidocStructure)).forEach((path) -> copyTo(path, targetFolder.resolve(sourceFolder.relativize(path))));
return targetFolder;
} catch (IOException e) {
throw new RuntimeException("Could not copy sample asciidoc structure", e);
}
}
private static void copyTo(Path sourcePath, Path targetPath) {
try {
createDirectories(targetPath.getParent());
copy(sourcePath, targetPath, REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException("Could not copy source path to target path", e);
}
}
private static Path temporaryPath(String content) {
try {
Path path = TEMPORARY_FOLDER.newFolder().toPath().resolve("tmp").resolve(sha256Hex(content) + ".adoc");
createDirectories(path.getParent());
write(path, content.getBytes(UTF_8));
return path;
} catch (IOException e) {
throw new RuntimeException("Could not write content to temporary path", e);
}
}
private AsciidocPage asciidocPage(Path rootFolder, String asciidocFileName) {
return asciidocPage(rootFolder.resolve(asciidocFileName));
}
private AsciidocPage asciidocPage(Path contentPath) {
return new TestAsciidocPage(contentPath);
}
private AsciidocPage asciidocPage(String content) {
return asciidocPage(temporaryPath(content));
}
private static class TestAsciidocPage implements AsciidocPage {
private final Path path;
TestAsciidocPage(Path path) {
this.path = path;
}
@Override
public Path path() {
return this.path;
}
@Override
public List<AsciidocPage> children() {
return emptyList();
}
}
private static void setDefaultCharset(Charset charset) {
try {
Field defaultCharsetField = Charset.class.getDeclaredField("defaultCharset");
defaultCharsetField.setAccessible(true);
defaultCharsetField.set(null, charset);
} catch (Exception e) {
throw new RuntimeException("Could not set default charset", e);
}
}
}
| #145: add tests for blocks that support titles
| asciidoc-confluence-publisher-converter/src/test/java/org/sahli/asciidoc/confluence/publisher/converter/AsciidocConfluencePageTest.java | #145: add tests for blocks that support titles | <ide><path>sciidoc-confluence-publisher-converter/src/test/java/org/sahli/asciidoc/confluence/publisher/converter/AsciidocConfluencePageTest.java
<ide> }
<ide>
<ide> @Test
<add> public void renderConfluencePage_asciiDocWithListingAndTitle_returnsConfluencePageContentWithMacroWithNameNoFormatAndTitle() {
<add> // arrange
<add> String adocContent = ".A block title\n" +
<add> "----\n" +
<add> "import java.util.List;\n" +
<add> "----";
<add>
<add> // act
<add> AsciidocConfluencePage asciiDocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
<add>
<add> // assert
<add> String expectedContent = "<ac:structured-macro ac:name=\"noformat\">" +
<add> "<ac:parameter ac:name=\"title\">A block title</ac:parameter>" +
<add> "<ac:plain-text-body><![CDATA[import java.util.List;]]></ac:plain-text-body>" +
<add> "</ac:structured-macro>";
<add> assertThat(asciiDocConfluencePage.content(), is(expectedContent));
<add> }
<add>
<add> @Test
<ide> public void renderConfluencePage_asciiDocWithSourceListing_returnsConfluencePageContentWithMacroWithNameCode() {
<ide> // arrange
<ide> String adocContent = "[source]\n" +
<ide>
<ide> // assert
<ide> String expectedContent = "<a href=\"http://www.foo.ch\"><ac:image ac:height=\"200\" ac:width=\"300\"><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image></a>";
<add> assertThat(asciidocConfluencePage.content(), is(expectedContent));
<add> }
<add>
<add> @Test
<add> public void renderConfluencePage_asciiDocWithImageWithTitle_returnsConfluencePageContentWithImageWithTitle() {
<add> String adocContent = ".A beautiful sunset\n" +
<add> "image::sunset.jpg[]";
<add>
<add> AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage(prependTitle(adocContent)), UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
<add>
<add> String expectedContent = "<ac:image ac:title=\"A beautiful sunset\" ac:alt=\"A beautiful sunset\"><ri:attachment ri:filename=\"sunset.jpg\"></ri:attachment></ac:image><div class=\"cp-image-title\"><em>Figure 1. A beautiful sunset</em></div>";
<ide> assertThat(asciidocConfluencePage.content(), is(expectedContent));
<ide> }
<ide>
<ide> }
<ide>
<ide> @Test
<add> public void renderConfluencePage_asciiDocWithUnorderedListAndTitle_returnsConfluencePageHavingCorrectUnorderedListAndTitleMarkup() {
<add> // arrange
<add> String adocContent = ".An unordered list title\n" +
<add> "* L1-1\n" +
<add> "* L1-2\n";
<add>
<add> AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
<add>
<add> // act
<add> AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
<add>
<add> // assert
<add> String expectedContent = "<div class=\"cp-ulist-title\"><em>An unordered list title</em></div>" + "<ul><li>L1-1</li><li>L1-2</li></ul>";
<add> assertThat(asciidocConfluencePage.content(), is(expectedContent));
<add> }
<add>
<add> @Test
<ide> public void renderConfluencePage_asciiDocWithOrderedList_returnsConfluencePageHavingCorrectOrderedListMarkup() {
<ide> // arrange
<ide> String adocContent = ". L1-1\n" +
<ide>
<ide> // assert
<ide> String expectedContent = "<ol><li>L1-1<ol><li>L2-1<ol><li>L3-1<ol><li>L4-1<ol><li>L5-1</li></ol></li></ol></li></ol></li></ol></li><li>L1-2</li></ol>";
<add> assertThat(asciidocConfluencePage.content(), is(expectedContent));
<add> }
<add>
<add> @Test
<add> public void renderConfluencePage_asciiDocWithOrderedListAndTitle_returnsConfluencePageHavingCorrectOrderedListAndTitleMarkup() {
<add> // arrange
<add> String adocContent = ".An ordered list title\n" +
<add> ". L1-1\n" +
<add> ". L1-2\n";
<add> AsciidocPage asciidocPage = asciidocPage(prependTitle(adocContent));
<add>
<add> // act
<add> AsciidocConfluencePage asciidocConfluencePage = newAsciidocConfluencePage(asciidocPage, UTF_8, TEMPLATES_FOLDER, dummyAssetsTargetPath());
<add>
<add> // assert
<add> String expectedContent = "<div class=\"cp-olist-title\"><em>An ordered list title</em></div>" +
<add> "<ol><li>L1-1</li><li>L1-2</li></ol>";
<ide> assertThat(asciidocConfluencePage.content(), is(expectedContent));
<ide> }
<ide> |
|
Java | apache-2.0 | 7265e7d932c6452d5db2f1981596aa822f5c97ec | 0 | nicoulaj/checksum-maven-plugin | /*
* checksum-maven-plugin - http://checksum-maven-plugin.nicoulaj.net
* Copyright © 2010-2021 checksum-maven-plugin contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.nicoulaj.maven.plugins.checksum.mojo;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* Compute project dependencies checksum digests and store them in a summary file.
*
* @author <a href="mailto:[email protected]">Julien Nicoulaud</a>
* @since 1.0
* @version $Id: $Id
*/
@Mojo(
name = DependenciesMojo.NAME,
defaultPhase = LifecyclePhase.VERIFY,
requiresProject = true,
inheritByDefault = false,
requiresDependencyResolution = ResolutionScope.RUNTIME,
threadSafe = true )
public class DependenciesMojo
extends AbstractChecksumMojo
{
/**
* The mojo name.
*/
public static final String NAME = "dependencies";
/**
* Indicates whether the build will store checksums in separate files (one file per algorithm per artifact).
*
* @since 1.0
*/
@Parameter( defaultValue = "false" )
protected boolean individualFiles;
/**
* The directory where output files will be stored. Leave unset to have each file next to the source file.
*
* @since 1.0
*/
@Parameter( defaultValue = "${project.build.directory}" )
protected String individualFilesOutputDirectory;
/**
* Indicates whether the build will store checksums to a single CSV summary file.
*
* @since 1.0
*/
@Parameter( defaultValue = "true" )
protected boolean csvSummary;
/**
* The name of the summary file created if the option is activated.
*
* @see #csvSummary
* @since 1.0
*/
@Parameter( defaultValue = "dependencies-checksums.csv" )
protected String csvSummaryFile;
/**
* Indicates whether the build will store checksums to a single XML summary file.
*
* @since 1.0
*/
@Parameter( defaultValue = "false" )
protected boolean xmlSummary;
/**
* The name of the summary file created if the option is activated.
*
* @see #xmlSummary
* @since 1.0
*/
@Parameter( defaultValue = "dependencies-checksums.xml" )
protected String xmlSummaryFile;
/**
* Indicates whether the build will store checksums to a single shasum summary file.
*
* @since 1.3
*/
@Parameter( defaultValue = "false" )
protected boolean shasumSummary;
/**
* The name of the summary file created if the option is activated.
*
* @see #shasumSummary
* @since 1.3
*/
@Parameter( defaultValue = "dependencies-checksums.sha" )
protected String shasumSummaryFile;
/**
* The dependency scopes to include.
*
* <p>Allowed values are compile, test, runtime, provided and system.<br>All scopes are included by default.
*
* <p> Use the following syntax:
* <pre><scopes>
* <scope>compile<scope>
* <scope>runtime<scope>
* </scopes></pre>
*
* @since 1.0
*/
@Parameter
protected List<String> scopes;
/**
* The dependency types to include.
*
* <p>All types are included by default.
*
* <p> Use the following syntax:
* <pre><types>
* <type>jar<type>
* <type>zip<type>
* </types></pre>
*
* @since 1.0
*/
@Parameter
protected List<String> types;
/**
* Transitive dependencies or only direct dependencies.
*
* @since 1.0
*/
@Parameter( property = "transitive", defaultValue = "false" )
protected boolean transitive;
/**
* Constructor.
*/
public DependenciesMojo() {
super(false, true, true);
}
/**
* {@inheritDoc}
*
* Build the list of files from which digests should be generated.
*
* <p>The list is composed of the project dependencies.</p>
*/
@Override
protected List<ChecksumFile> getFilesToProcess()
{
List<ChecksumFile> files = new LinkedList<>();
Set<Artifact> artifacts = transitive ? project.getArtifacts() : project.getDependencyArtifacts();
for ( Artifact artifact : artifacts )
{
if ( ( scopes == null || scopes.contains( artifact.getScope() ) ) && ( types == null || types.contains(
artifact.getType() ) ) && artifact.getFile() != null )
{
files.add( new ChecksumFile( "", artifact.getFile(), artifact.getType(), artifact.getClassifier() ) );
}
}
return files;
}
/** {@inheritDoc} */
@Override
protected boolean isIndividualFiles()
{
return individualFiles;
}
/** {@inheritDoc} */
@Override
protected String getIndividualFilesOutputDirectory()
{
return individualFilesOutputDirectory;
}
/** {@inheritDoc} */
@Override
protected boolean isCsvSummary()
{
return csvSummary;
}
/** {@inheritDoc} */
@Override
protected String getCsvSummaryFile()
{
return csvSummaryFile;
}
/** {@inheritDoc} */
@Override
protected boolean isXmlSummary()
{
return xmlSummary;
}
/** {@inheritDoc} */
@Override
protected String getXmlSummaryFile()
{
return xmlSummaryFile;
}
/** {@inheritDoc} */
@Override
protected boolean isShasumSummary()
{
return shasumSummary;
}
/** {@inheritDoc} */
@Override
protected String getShasumSummaryFile()
{
return shasumSummaryFile;
}
}
| src/main/java/net/nicoulaj/maven/plugins/checksum/mojo/DependenciesMojo.java | /*
* checksum-maven-plugin - http://checksum-maven-plugin.nicoulaj.net
* Copyright © 2010-2021 checksum-maven-plugin contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.nicoulaj.maven.plugins.checksum.mojo;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* Compute project dependencies checksum digests and store them in a summary file.
*
* @author <a href="mailto:[email protected]">Julien Nicoulaud</a>
* @since 1.0
* @version $Id: $Id
*/
@Mojo(
name = DependenciesMojo.NAME,
defaultPhase = LifecyclePhase.VERIFY,
requiresProject = true,
inheritByDefault = false,
requiresDependencyResolution = ResolutionScope.RUNTIME,
threadSafe = true )
public class DependenciesMojo
extends AbstractChecksumMojo
{
/**
* The mojo name.
*/
public static final String NAME = "dependencies";
/**
* Indicates whether the build will store checksums in separate files (one file per algorithm per artifact).
*
* @since 1.0
*/
@Parameter( defaultValue = "false" )
protected boolean individualFiles;
/**
* The directory where output files will be stored. Leave unset to have each file next to the source file.
*
* @since 1.0
*/
@Parameter( defaultValue = "${project.build.directory}" )
protected String individualFilesOutputDirectory;
/**
* Indicates whether the build will store checksums to a single CSV summary file.
*
* @since 1.0
*/
@Parameter( defaultValue = "true" )
protected boolean csvSummary;
/**
* The name of the summary file created if the option is activated.
*
* @see #csvSummary
* @since 1.0
*/
@Parameter( defaultValue = "dependencies-checksums.csv" )
protected String csvSummaryFile;
/**
* Indicates whether the build will store checksums to a single XML summary file.
*
* @since 1.0
*/
@Parameter( defaultValue = "false" )
protected boolean xmlSummary;
/**
* The name of the summary file created if the option is activated.
*
* @see #xmlSummary
* @since 1.0
*/
@Parameter( defaultValue = "dependencies-checksums.xml" )
protected String xmlSummaryFile;
/**
* Indicates whether the build will store checksums to a single shasum summary file.
*
* @since 1.3
*/
@Parameter( defaultValue = "false" )
protected boolean shasumSummary;
/**
* The name of the summary file created if the option is activated.
*
* @see #shasumSummary
* @since 1.3
*/
@Parameter( defaultValue = "dependencies-checksums.sha" )
protected String shasumSummaryFile;
/**
* The dependency scopes to include.
*
* <p>Allowed values are compile, test, runtime, provided and system.<br>All scopes are included by default.
*
* <p> Use the following syntax:
* <pre><scopes>
* <scope>compile<scope>
* <scope>runtime<scope>
* </scopes></pre>
*
* @since 1.0
*/
@Parameter
protected List<String> scopes;
/**
* The dependency types to include.
*
* <p>All types are included by default.
*
* <p> Use the following syntax:
* <pre><types>
* <type>jar<type>
* <type>zip<type>
* </types></pre>
*
* @since 1.0
*/
@Parameter
protected List<String> types;
/**
* Transitive dependencies or only direct dependencies.
*
* @since 1.0
*/
@Parameter( defaultValue = "false" )
protected boolean transitive;
/**
* Constructor.
*/
public DependenciesMojo() {
super(false, true, true);
}
/**
* {@inheritDoc}
*
* Build the list of files from which digests should be generated.
*
* <p>The list is composed of the project dependencies.</p>
*/
@Override
protected List<ChecksumFile> getFilesToProcess()
{
List<ChecksumFile> files = new LinkedList<>();
Set<Artifact> artifacts = transitive ? project.getArtifacts() : project.getDependencyArtifacts();
for ( Artifact artifact : artifacts )
{
if ( ( scopes == null || scopes.contains( artifact.getScope() ) ) && ( types == null || types.contains(
artifact.getType() ) ) && artifact.getFile() != null )
{
files.add( new ChecksumFile( "", artifact.getFile(), artifact.getType(), artifact.getClassifier() ) );
}
}
return files;
}
/** {@inheritDoc} */
@Override
protected boolean isIndividualFiles()
{
return individualFiles;
}
/** {@inheritDoc} */
@Override
protected String getIndividualFilesOutputDirectory()
{
return individualFilesOutputDirectory;
}
/** {@inheritDoc} */
@Override
protected boolean isCsvSummary()
{
return csvSummary;
}
/** {@inheritDoc} */
@Override
protected String getCsvSummaryFile()
{
return csvSummaryFile;
}
/** {@inheritDoc} */
@Override
protected boolean isXmlSummary()
{
return xmlSummary;
}
/** {@inheritDoc} */
@Override
protected String getXmlSummaryFile()
{
return xmlSummaryFile;
}
/** {@inheritDoc} */
@Override
protected boolean isShasumSummary()
{
return shasumSummary;
}
/** {@inheritDoc} */
@Override
protected String getShasumSummaryFile()
{
return shasumSummaryFile;
}
}
| enable transitive property
| src/main/java/net/nicoulaj/maven/plugins/checksum/mojo/DependenciesMojo.java | enable transitive property | <ide><path>rc/main/java/net/nicoulaj/maven/plugins/checksum/mojo/DependenciesMojo.java
<ide> *
<ide> * @since 1.0
<ide> */
<del> @Parameter( defaultValue = "false" )
<add> @Parameter( property = "transitive", defaultValue = "false" )
<ide> protected boolean transitive;
<ide>
<ide> /** |
|
Java | bsd-2-clause | 1ae90b95cf9369514ac9f5a6b0b1e2bf2fde3239 | 0 | biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej | core/tools/src/main/java/imagej/core/tools/FloodFiller.java | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2012 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej.core.tools;
import imagej.data.ChannelCollection;
import imagej.data.Dataset;
import imagej.data.DrawingTool;
import imagej.util.RealRect;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import net.imglib2.RandomAccess;
import net.imglib2.meta.Axes;
import net.imglib2.type.numeric.RealType;
/**
* This class, which does flood filling, is used by the FloodFillTool. It was
* adapted from IJ1's FloodFiller class. That class implements the flood filling
* code used by IJ1's macro language and IJ1's particle analyzer. The Wikipedia
* article at "http://en.wikipedia.org/wiki/Flood_fill" has a good description
* of the algorithm used here as well as examples in C and Java.
*
* @author Wayne Rasband
* @author Barry DeZonia
*/
public class FloodFiller {
private final DrawingTool tool;
private int channelAxis;
private int uAxis;
private int vAxis;
private final StackOfLongs uStack;
private final StackOfLongs vStack;
/**
* Constructs a FloodFiller from a given DrawingTool. The FloodFiller uses the
* DrawingTool to fill a region of contiguous pixels in a plane of a Dataset.
*/
public FloodFiller(final DrawingTool tool) {
this.tool = tool;
this.channelAxis = tool.getDataset().getAxisIndex(Axes.CHANNEL);
this.uAxis = -1;
this.vAxis = -1;
this.uStack = new StackOfLongs();
this.vStack = new StackOfLongs();
}
/**
* Does a 4-connected flood fill using the current fill/draw value. Returns
* true if any pixels actually changed and false otherwise.
*/
public boolean fill4(final long u0, final long v0, final long[] position) {
final Dataset ds = tool.getDataset();
final RandomAccess<? extends RealType<?>> accessor =
ds.getImgPlus().randomAccess();
accessor.setPosition(position);
uAxis = tool.getUAxis();
vAxis = tool.getVAxis();
final ChannelCollection fillValues = tool.getChannels();
// avoid degenerate case
if (matches(accessor,u0,v0,fillValues)) return false;
final ChannelCollection origValues = getValues(accessor, u0, v0);
final long maxU = ds.dimension(uAxis) - 1;
final long maxV = ds.dimension(vAxis) - 1;
uStack.clear();
vStack.clear();
push(u0, v0);
while (!uStack.isEmpty()) {
final long u = popU();
final long v = popV();
if (!matches(accessor,u,v,origValues)) continue;
long u1 = u;
long u2 = u;
// find start of scan-line
while (u1>=0 && matches(accessor,u1,v,origValues)) u1--;
u1++;
// find end of scan-line
while (u2<=maxU && matches(accessor,u2,v,origValues)) u2++;
u2--;
// fill scan-line
tool.drawLine(u1, v, u2, v);
// find scan-lines above this one
boolean inScanLine = false;
for (long i=u1; i<=u2; i++) {
if (!inScanLine && v>0 && matches(accessor,i,v-1,origValues))
{push(i, v-1); inScanLine = true;}
else if (inScanLine && v>0 &&
!matches(accessor,i,v-1,origValues))
inScanLine = false;
}
// find scan-lines below this one
inScanLine = false;
for (long i=u1; i<=u2; i++) {
if (!inScanLine && v<maxV &&
matches(accessor,i,v+1,origValues))
{push(i, v+1); inScanLine = true;}
else if (inScanLine && v<maxV &&
!matches(accessor,i,v+1,origValues))
inScanLine = false;
}
}
// System.out.println("Stack allocated (but not necessarily used) "+uStack.stack.length);
return true;
}
/**
* Does an 8-connected flood fill using the current fill/draw value. Returns
* true if any pixels actually changed and false otherwise.
*/
public boolean fill8(final long u0, final long v0, final long[] position) {
final Dataset ds = tool.getDataset();
final RandomAccess<? extends RealType<?>> accessor =
ds.getImgPlus().randomAccess();
accessor.setPosition(position);
uAxis = tool.getUAxis();
vAxis = tool.getVAxis();
final ChannelCollection fillValues = tool.getChannels();
// avoid degenerate case
if (matches(accessor,u0,v0,fillValues)) return false;
final ChannelCollection origValues = getValues(accessor, u0, v0);
final long maxU = ds.dimension(uAxis) - 1;
final long maxV = ds.dimension(vAxis) - 1;
uStack.clear();
vStack.clear();
push(u0, v0);
while(!uStack.isEmpty()) {
final long u = popU();
final long v = popV();
long u1 = u;
long u2 = u;
if (matches(accessor,u,v,origValues)) {
// find start of scan-line
while (u1>=0 && matches(accessor,u1,v,origValues)) u1--;
u1++;
// find end of scan-line
while (u2<=maxU && matches(accessor,u2,v,origValues)) u2++;
u2--;
tool.drawLine(u1, v, u2, v); // fill scan-line
}
if (v > 0) {
if (u1 > 0) {
if (matches(accessor,u1-1,v-1,origValues)) {
push(u1-1, v-1);
}
}
if (u2 < maxU) {
if (matches(accessor,u2+1,v-1,origValues)) {
push(u2+1, v-1);
}
}
}
if (v < maxV) {
if (u1 > 0) {
if (matches(accessor,u1-1,v+1,origValues)) {
push(u1-1, v+1);
}
}
if (u2 < maxU) {
if (matches(accessor,u2+1,v+1,origValues)) {
push(u2+1, v+1);
}
}
}
// find scan-lines above this one
boolean inScanLine = false;
for (long i=u1; i<=u2; i++) {
if (!inScanLine && v>0 && matches(accessor,i,v-1,origValues))
{push(i, v-1); inScanLine = true;}
else if (inScanLine && v>0 &&
!matches(accessor,i,v-1,origValues))
inScanLine = false;
}
// find scan-lines below this one
inScanLine = false;
for (long i=u1; i<=u2; i++) {
if (!inScanLine && v<maxV &&
matches(accessor,i,v+1,origValues))
{push(i, v+1); inScanLine = true;}
else if (inScanLine && v<maxV &&
!matches(accessor,i,v+1,origValues))
inScanLine = false;
}
}
// System.out.println("Stack allocated (but not necessarily used) "+uStack.stack.length);
return true;
}
/**
* In IJ1 this method is used by the particle analyzer to remove interior
* holes from particle masks.
*/
public void particleAnalyzerFill(
long u0, long v0, long[] position, double level1, double level2,
DrawingTool maskTool, RealRect bounds)
{
final Dataset ds = tool.getDataset();
// TODO - is this a bogus limitation
if ((channelAxis != -1) || (ds.dimension(channelAxis) != 1)) {
throw new IllegalArgumentException(
"particle analyzer cannot support multiple channels");
}
final RandomAccess<? extends RealType<?>> acc =
ds.getImgPlus().randomAccess();
acc.setPosition(position);
uAxis = tool.getUAxis();
vAxis = tool.getVAxis();
long maxU = ds.dimension(uAxis) - 1;
long maxV = ds.dimension(vAxis) - 1;
long numChan = ds.dimension(channelAxis);
setValues(maskTool, numChan, 0);
// FIXME TODO - fill plane or roi of plane of maskTool?
// Decide between fill() or fill(RealRect)
maskTool.fill();
setValues(maskTool, numChan, 255);
uStack.clear();
vStack.clear();
push(u0, v0);
while(!uStack.isEmpty()) {
long u = popU();
long v = popV();
if (!inParticle(acc,u,v,level1,level2)) continue;
long u1 = u;
long u2 = u;
// find start of scan-line
while (inParticle(acc,u1,v,level1,level2) && u1>=0) u1--;
u1++;
// find end of scan-line
while (inParticle(acc,u2,v,level1,level2) && u2<=maxU) u2++;
u2--;
// fill scan-line in mask
maskTool.drawLine(
(long) (u1-bounds.x), (long) (v-bounds.y),
(long) (u2-bounds.x), (long) (v-bounds.y));
// fill scan-line in image
tool.drawLine(u1, v, u2, v);
boolean inScanLine = false;
if (u1>0) u1--;
if (u2<maxU) u2++;
for (long i=u1; i<=u2; i++) { // find scan-lines above this one
if (!inScanLine && v>0 && inParticle(acc,i,v-1,level1,level2))
{push(i, v-1); inScanLine = true;}
else if (inScanLine && v>0 && !inParticle(acc,i,v-1,level1,level2))
inScanLine = false;
}
inScanLine = false;
for (long i=u1; i<=u2; i++) { // find scan-lines below this one
if (!inScanLine && v<maxV && inParticle(acc,i,v+1,level1,level2))
{push(i, v+1); inScanLine = true;}
else if (inScanLine && v<maxV && !inParticle(acc,i,v+1,level1,level2))
inScanLine = false;
}
}
}
// -- private helpers --
/**
* Returns true if value of pixel is inside a given range
*/
private boolean inParticle(
RandomAccess<? extends RealType<?>> accessor, long u, long v,
double level1, double level2)
{
accessor.setPosition(u,uAxis);
accessor.setPosition(v,vAxis);
double val = accessor.get().getRealDouble();
return val>=level1 && val<=level2;
}
private void setValues(DrawingTool tool, long numChan, double value) {
final List<Double> values = new LinkedList<Double>();
for (long i = 0; i < numChan; i++)
values.add(value);
final ChannelCollection channels = new ChannelCollection(values);
tool.setChannels(channels);
}
/**
* Returns true if the current pixel located at the given (u,v) coordinates is
* the same as the specified color or gray values.
*/
private boolean matches(
final RandomAccess<? extends RealType<?>> accessor, final long u,
final long v, final ChannelCollection channels)
{
accessor.setPosition(u, uAxis);
accessor.setPosition(v, vAxis);
// 0 channel image?
if (channelAxis == -1) {
final double val = accessor.get().getRealDouble();
return val == channels.getChannelValue(0);
}
// else image has 1 or more channels
long numChan = tool.getDataset().dimension(channelAxis);
for (long c = 0; c < numChan; c++) {
accessor.setPosition(c, channelAxis);
double value = accessor.get().getRealDouble();
// TODO - do we need a "near" rather than "equal" here?
if (value != channels.getChannelValue(c)) return false;
}
return true;
}
/**
* Records the values of all the channels at a given (u,v) coord in a Dataset.
* The non-UV coords must be set on the accessor before calling this method.
*/
private ChannelCollection getValues(
final RandomAccess<? extends RealType<?>> accessor,
final long u, final long v)
{
final List<Double> channels = new LinkedList<Double>();
accessor.setPosition(u, uAxis);
accessor.setPosition(v, vAxis);
long numChannels = 1;
if (channelAxis != -1)
numChannels = tool.getDataset().dimension(channelAxis);
for (long c = 0; c < numChannels; c++) {
if (channelAxis != -1) accessor.setPosition(c, channelAxis);
final double val = accessor.get().getRealDouble();
channels.add(val);
}
return new ChannelCollection(channels);
}
/**
* Pushes the specified (u,v) point on the working stacks.
*/
private void push(final long u, final long v) {
uStack.push(u);
vStack.push(v);
}
/** Pops a U value of the working U stack. */
private long popU() {
return uStack.pop();
}
/** Pops a V value of the working V stack. */
private long popV() {
return vStack.pop();
}
/** To minimize object creations/deletions we want a stack of primitives. */
private class StackOfLongs {
private int top;
private long[] stack;
public StackOfLongs() {
top = -1;
stack = new long[400];
}
public boolean isEmpty() {
return top < 0;
}
public void clear() {
top = -1;
}
public void push(final long value) {
if (top == stack.length - 1)
stack = Arrays.copyOf(stack, stack.length * 2);
top++;
stack[top] = value;
}
public long pop() {
if (top < 0) throw new IllegalArgumentException("can't pop empty stack");
final long value = stack[top];
top--;
return value;
}
}
}
| Delete old FloodFiller copy
This used to be revision r5299.
| core/tools/src/main/java/imagej/core/tools/FloodFiller.java | Delete old FloodFiller copy | <ide><path>ore/tools/src/main/java/imagej/core/tools/FloodFiller.java
<del>/*
<del> * #%L
<del> * ImageJ software for multidimensional image processing and analysis.
<del> * %%
<del> * Copyright (C) 2009 - 2012 Board of Regents of the University of
<del> * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
<del> * Institute of Molecular Cell Biology and Genetics.
<del> * %%
<del> * Redistribution and use in source and binary forms, with or without
<del> * modification, are permitted provided that the following conditions are met:
<del> *
<del> * 1. Redistributions of source code must retain the above copyright notice,
<del> * this list of conditions and the following disclaimer.
<del> * 2. Redistributions in binary form must reproduce the above copyright notice,
<del> * this list of conditions and the following disclaimer in the documentation
<del> * and/or other materials provided with the distribution.
<del> *
<del> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
<del> * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
<del> * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
<del> * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
<del> * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
<del> * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
<del> * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
<del> * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
<del> * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
<del> * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
<del> * POSSIBILITY OF SUCH DAMAGE.
<del> *
<del> * The views and conclusions contained in the software and documentation are
<del> * those of the authors and should not be interpreted as representing official
<del> * policies, either expressed or implied, of any organization.
<del> * #L%
<del> */
<del>
<del>package imagej.core.tools;
<del>
<del>import imagej.data.ChannelCollection;
<del>import imagej.data.Dataset;
<del>import imagej.data.DrawingTool;
<del>import imagej.util.RealRect;
<del>
<del>import java.util.Arrays;
<del>import java.util.LinkedList;
<del>import java.util.List;
<del>
<del>import net.imglib2.RandomAccess;
<del>import net.imglib2.meta.Axes;
<del>import net.imglib2.type.numeric.RealType;
<del>
<del>/**
<del> * This class, which does flood filling, is used by the FloodFillTool. It was
<del> * adapted from IJ1's FloodFiller class. That class implements the flood filling
<del> * code used by IJ1's macro language and IJ1's particle analyzer. The Wikipedia
<del> * article at "http://en.wikipedia.org/wiki/Flood_fill" has a good description
<del> * of the algorithm used here as well as examples in C and Java.
<del> *
<del> * @author Wayne Rasband
<del> * @author Barry DeZonia
<del> */
<del>public class FloodFiller {
<del>
<del> private final DrawingTool tool;
<del> private int channelAxis;
<del> private int uAxis;
<del> private int vAxis;
<del> private final StackOfLongs uStack;
<del> private final StackOfLongs vStack;
<del>
<del> /**
<del> * Constructs a FloodFiller from a given DrawingTool. The FloodFiller uses the
<del> * DrawingTool to fill a region of contiguous pixels in a plane of a Dataset.
<del> */
<del> public FloodFiller(final DrawingTool tool) {
<del> this.tool = tool;
<del> this.channelAxis = tool.getDataset().getAxisIndex(Axes.CHANNEL);
<del> this.uAxis = -1;
<del> this.vAxis = -1;
<del> this.uStack = new StackOfLongs();
<del> this.vStack = new StackOfLongs();
<del> }
<del>
<del> /**
<del> * Does a 4-connected flood fill using the current fill/draw value. Returns
<del> * true if any pixels actually changed and false otherwise.
<del> */
<del> public boolean fill4(final long u0, final long v0, final long[] position) {
<del> final Dataset ds = tool.getDataset();
<del> final RandomAccess<? extends RealType<?>> accessor =
<del> ds.getImgPlus().randomAccess();
<del> accessor.setPosition(position);
<del> uAxis = tool.getUAxis();
<del> vAxis = tool.getVAxis();
<del> final ChannelCollection fillValues = tool.getChannels();
<del> // avoid degenerate case
<del> if (matches(accessor,u0,v0,fillValues)) return false;
<del> final ChannelCollection origValues = getValues(accessor, u0, v0);
<del> final long maxU = ds.dimension(uAxis) - 1;
<del> final long maxV = ds.dimension(vAxis) - 1;
<del> uStack.clear();
<del> vStack.clear();
<del> push(u0, v0);
<del> while (!uStack.isEmpty()) {
<del> final long u = popU();
<del> final long v = popV();
<del> if (!matches(accessor,u,v,origValues)) continue;
<del> long u1 = u;
<del> long u2 = u;
<del> // find start of scan-line
<del> while (u1>=0 && matches(accessor,u1,v,origValues)) u1--;
<del> u1++;
<del> // find end of scan-line
<del> while (u2<=maxU && matches(accessor,u2,v,origValues)) u2++;
<del> u2--;
<del> // fill scan-line
<del> tool.drawLine(u1, v, u2, v);
<del> // find scan-lines above this one
<del> boolean inScanLine = false;
<del> for (long i=u1; i<=u2; i++) {
<del> if (!inScanLine && v>0 && matches(accessor,i,v-1,origValues))
<del> {push(i, v-1); inScanLine = true;}
<del> else if (inScanLine && v>0 &&
<del> !matches(accessor,i,v-1,origValues))
<del> inScanLine = false;
<del> }
<del> // find scan-lines below this one
<del> inScanLine = false;
<del> for (long i=u1; i<=u2; i++) {
<del> if (!inScanLine && v<maxV &&
<del> matches(accessor,i,v+1,origValues))
<del> {push(i, v+1); inScanLine = true;}
<del> else if (inScanLine && v<maxV &&
<del> !matches(accessor,i,v+1,origValues))
<del> inScanLine = false;
<del> }
<del> }
<del> // System.out.println("Stack allocated (but not necessarily used) "+uStack.stack.length);
<del> return true;
<del> }
<del>
<del> /**
<del> * Does an 8-connected flood fill using the current fill/draw value. Returns
<del> * true if any pixels actually changed and false otherwise.
<del> */
<del> public boolean fill8(final long u0, final long v0, final long[] position) {
<del> final Dataset ds = tool.getDataset();
<del> final RandomAccess<? extends RealType<?>> accessor =
<del> ds.getImgPlus().randomAccess();
<del> accessor.setPosition(position);
<del> uAxis = tool.getUAxis();
<del> vAxis = tool.getVAxis();
<del> final ChannelCollection fillValues = tool.getChannels();
<del> // avoid degenerate case
<del> if (matches(accessor,u0,v0,fillValues)) return false;
<del> final ChannelCollection origValues = getValues(accessor, u0, v0);
<del> final long maxU = ds.dimension(uAxis) - 1;
<del> final long maxV = ds.dimension(vAxis) - 1;
<del> uStack.clear();
<del> vStack.clear();
<del> push(u0, v0);
<del> while(!uStack.isEmpty()) {
<del> final long u = popU();
<del> final long v = popV();
<del> long u1 = u;
<del> long u2 = u;
<del> if (matches(accessor,u,v,origValues)) {
<del> // find start of scan-line
<del> while (u1>=0 && matches(accessor,u1,v,origValues)) u1--;
<del> u1++;
<del> // find end of scan-line
<del> while (u2<=maxU && matches(accessor,u2,v,origValues)) u2++;
<del> u2--;
<del> tool.drawLine(u1, v, u2, v); // fill scan-line
<del> }
<del> if (v > 0) {
<del> if (u1 > 0) {
<del> if (matches(accessor,u1-1,v-1,origValues)) {
<del> push(u1-1, v-1);
<del> }
<del> }
<del> if (u2 < maxU) {
<del> if (matches(accessor,u2+1,v-1,origValues)) {
<del> push(u2+1, v-1);
<del> }
<del> }
<del> }
<del> if (v < maxV) {
<del> if (u1 > 0) {
<del> if (matches(accessor,u1-1,v+1,origValues)) {
<del> push(u1-1, v+1);
<del> }
<del> }
<del> if (u2 < maxU) {
<del> if (matches(accessor,u2+1,v+1,origValues)) {
<del> push(u2+1, v+1);
<del> }
<del> }
<del> }
<del> // find scan-lines above this one
<del> boolean inScanLine = false;
<del> for (long i=u1; i<=u2; i++) {
<del> if (!inScanLine && v>0 && matches(accessor,i,v-1,origValues))
<del> {push(i, v-1); inScanLine = true;}
<del> else if (inScanLine && v>0 &&
<del> !matches(accessor,i,v-1,origValues))
<del> inScanLine = false;
<del> }
<del> // find scan-lines below this one
<del> inScanLine = false;
<del> for (long i=u1; i<=u2; i++) {
<del> if (!inScanLine && v<maxV &&
<del> matches(accessor,i,v+1,origValues))
<del> {push(i, v+1); inScanLine = true;}
<del> else if (inScanLine && v<maxV &&
<del> !matches(accessor,i,v+1,origValues))
<del> inScanLine = false;
<del> }
<del> }
<del> // System.out.println("Stack allocated (but not necessarily used) "+uStack.stack.length);
<del> return true;
<del> }
<del>
<del> /**
<del> * In IJ1 this method is used by the particle analyzer to remove interior
<del> * holes from particle masks.
<del> */
<del> public void particleAnalyzerFill(
<del> long u0, long v0, long[] position, double level1, double level2,
<del> DrawingTool maskTool, RealRect bounds)
<del> {
<del> final Dataset ds = tool.getDataset();
<del> // TODO - is this a bogus limitation
<del> if ((channelAxis != -1) || (ds.dimension(channelAxis) != 1)) {
<del> throw new IllegalArgumentException(
<del> "particle analyzer cannot support multiple channels");
<del> }
<del> final RandomAccess<? extends RealType<?>> acc =
<del> ds.getImgPlus().randomAccess();
<del> acc.setPosition(position);
<del> uAxis = tool.getUAxis();
<del> vAxis = tool.getVAxis();
<del> long maxU = ds.dimension(uAxis) - 1;
<del> long maxV = ds.dimension(vAxis) - 1;
<del> long numChan = ds.dimension(channelAxis);
<del> setValues(maskTool, numChan, 0);
<del> // FIXME TODO - fill plane or roi of plane of maskTool?
<del> // Decide between fill() or fill(RealRect)
<del> maskTool.fill();
<del> setValues(maskTool, numChan, 255);
<del> uStack.clear();
<del> vStack.clear();
<del> push(u0, v0);
<del> while(!uStack.isEmpty()) {
<del> long u = popU();
<del> long v = popV();
<del> if (!inParticle(acc,u,v,level1,level2)) continue;
<del> long u1 = u;
<del> long u2 = u;
<del> // find start of scan-line
<del> while (inParticle(acc,u1,v,level1,level2) && u1>=0) u1--;
<del> u1++;
<del> // find end of scan-line
<del> while (inParticle(acc,u2,v,level1,level2) && u2<=maxU) u2++;
<del> u2--;
<del> // fill scan-line in mask
<del> maskTool.drawLine(
<del> (long) (u1-bounds.x), (long) (v-bounds.y),
<del> (long) (u2-bounds.x), (long) (v-bounds.y));
<del> // fill scan-line in image
<del> tool.drawLine(u1, v, u2, v);
<del> boolean inScanLine = false;
<del> if (u1>0) u1--;
<del> if (u2<maxU) u2++;
<del> for (long i=u1; i<=u2; i++) { // find scan-lines above this one
<del> if (!inScanLine && v>0 && inParticle(acc,i,v-1,level1,level2))
<del> {push(i, v-1); inScanLine = true;}
<del> else if (inScanLine && v>0 && !inParticle(acc,i,v-1,level1,level2))
<del> inScanLine = false;
<del> }
<del> inScanLine = false;
<del> for (long i=u1; i<=u2; i++) { // find scan-lines below this one
<del> if (!inScanLine && v<maxV && inParticle(acc,i,v+1,level1,level2))
<del> {push(i, v+1); inScanLine = true;}
<del> else if (inScanLine && v<maxV && !inParticle(acc,i,v+1,level1,level2))
<del> inScanLine = false;
<del> }
<del> }
<del> }
<del>
<del> // -- private helpers --
<del>
<del> /**
<del> * Returns true if value of pixel is inside a given range
<del> */
<del> private boolean inParticle(
<del> RandomAccess<? extends RealType<?>> accessor, long u, long v,
<del> double level1, double level2)
<del> {
<del> accessor.setPosition(u,uAxis);
<del> accessor.setPosition(v,vAxis);
<del> double val = accessor.get().getRealDouble();
<del> return val>=level1 && val<=level2;
<del> }
<del>
<del> private void setValues(DrawingTool tool, long numChan, double value) {
<del> final List<Double> values = new LinkedList<Double>();
<del> for (long i = 0; i < numChan; i++)
<del> values.add(value);
<del> final ChannelCollection channels = new ChannelCollection(values);
<del> tool.setChannels(channels);
<del> }
<del>
<del> /**
<del> * Returns true if the current pixel located at the given (u,v) coordinates is
<del> * the same as the specified color or gray values.
<del> */
<del> private boolean matches(
<del> final RandomAccess<? extends RealType<?>> accessor, final long u,
<del> final long v, final ChannelCollection channels)
<del> {
<del> accessor.setPosition(u, uAxis);
<del> accessor.setPosition(v, vAxis);
<del>
<del> // 0 channel image?
<del> if (channelAxis == -1) {
<del> final double val = accessor.get().getRealDouble();
<del> return val == channels.getChannelValue(0);
<del> }
<del>
<del> // else image has 1 or more channels
<del> long numChan = tool.getDataset().dimension(channelAxis);
<del> for (long c = 0; c < numChan; c++) {
<del> accessor.setPosition(c, channelAxis);
<del> double value = accessor.get().getRealDouble();
<del> // TODO - do we need a "near" rather than "equal" here?
<del> if (value != channels.getChannelValue(c)) return false;
<del> }
<del>
<del> return true;
<del> }
<del>
<del> /**
<del> * Records the values of all the channels at a given (u,v) coord in a Dataset.
<del> * The non-UV coords must be set on the accessor before calling this method.
<del> */
<del> private ChannelCollection getValues(
<del> final RandomAccess<? extends RealType<?>> accessor,
<del> final long u, final long v)
<del> {
<del> final List<Double> channels = new LinkedList<Double>();
<del> accessor.setPosition(u, uAxis);
<del> accessor.setPosition(v, vAxis);
<del> long numChannels = 1;
<del> if (channelAxis != -1)
<del> numChannels = tool.getDataset().dimension(channelAxis);
<del> for (long c = 0; c < numChannels; c++) {
<del> if (channelAxis != -1) accessor.setPosition(c, channelAxis);
<del> final double val = accessor.get().getRealDouble();
<del> channels.add(val);
<del> }
<del> return new ChannelCollection(channels);
<del> }
<del>
<del> /**
<del> * Pushes the specified (u,v) point on the working stacks.
<del> */
<del> private void push(final long u, final long v) {
<del> uStack.push(u);
<del> vStack.push(v);
<del> }
<del>
<del> /** Pops a U value of the working U stack. */
<del> private long popU() {
<del> return uStack.pop();
<del> }
<del>
<del> /** Pops a V value of the working V stack. */
<del> private long popV() {
<del> return vStack.pop();
<del> }
<del>
<del> /** To minimize object creations/deletions we want a stack of primitives. */
<del> private class StackOfLongs {
<del>
<del> private int top;
<del> private long[] stack;
<del>
<del> public StackOfLongs() {
<del> top = -1;
<del> stack = new long[400];
<del> }
<del>
<del> public boolean isEmpty() {
<del> return top < 0;
<del> }
<del>
<del> public void clear() {
<del> top = -1;
<del> }
<del>
<del> public void push(final long value) {
<del> if (top == stack.length - 1)
<del> stack = Arrays.copyOf(stack, stack.length * 2);
<del> top++;
<del> stack[top] = value;
<del> }
<del>
<del> public long pop() {
<del> if (top < 0) throw new IllegalArgumentException("can't pop empty stack");
<del> final long value = stack[top];
<del> top--;
<del> return value;
<del> }
<del> }
<del>
<del>} |
||
JavaScript | mit | a734d3659bcd5a026fd50ded6ab73bd9203dd9a4 | 0 | donghanji/pm | /*
* @version v.1.1.123.0
* @name Plugins Modules
* @author donghanji
* @datetime 2013-01-07
*
* @desc
//The aims of PM is that taking modules as the core to form a powerful plug-in library.
//This file is the core of PM,Modules.
//This is the first version of PM.
//The future of the PM, you and I, we us grow together...
*
*/
;(function(global,undefined){
//location pathname
var startPath = window.location.pathname,
//private property
class2type={},
toString=Object.prototype.toString;
//module object
var module={
version:'1.1.123.0',//version
options:{
'require':false,//whether open require mode
'timeout':7000,//.ms
'base':'',//base path
'dirs':{},//directories,include modules,plugins,mobile,pad,web
'alias':{},//module alias
'files':[],//not a module,a common file,there is no define method in it
'globals':{},//global variables
'sets':{},//module configuration
'coms':{},//one file ,multiple modules
'debug':false//whether open debug mode
},
util:{},
path:{}
};
//regx
var REGX={
'SLASHDIR':/^\//,
'BASEDIR':/.*(?=\/.*$)/,
'JSSUFFIX':/\.js$/,
'COMMENT':/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
'REQUIRE':/(?:^|[^.$])\brequire\s*\(\s*(["'])([^"'\s\)]+)\1\s*\)/g,
'REQUIRE_FUN':/^function \(\w*\)/,
'MODULENAME':/\/([\w.]+)?(?:\1)?$/,
'PLACEHOLDER_DIR':/\{(\S+)?\}(?:\1)?/
},
//status
STATUS={
'ERROR':-1,
'BEGIN':0,
'LOADING':1,
'LOADED':2,
'END':3
};
/*
* @anme util
* @desc
the private utilities,internal use only.
*
*/
(function(util){
util.extend=function(){
var options,
target=arguments[0]||{},
length=arguments.length,
i=1;
if(length === i){
target=this;
--i;
}
for(;i<length;i++){
options=arguments[i];
if(typeof options === 'object'){
for(var name in options){
target[name]=options[name];
}
}
}
return target;
};
//is* method,element attribute is *
util.extend({
type:function(value){
return value == null ?
String(value) :
class2type[toString.call(value)] || 'object';
},
isNumeric:function(value){
return !isNaN(parseFloat(value)) && isFinite(value);
},
isString:function(value){
return util.type(value) === 'string';
},
isFunction:function(value){
return util.type(value) === 'function';
},
isObject:function(value){
return util.type(value) === 'object';
},
isArray:function(value){
return util.type(value) === 'array';
}
});
//now time
util.now=function(){
return new Date().getTime();
};
//unique id
util.uid=function(){
return new Date().getTime()+Math.floor(Math.random()*1000000);
};
//is empty
util.isEmpty=function(val){
if(val === '' || val === undefined || val === null){
return true;
}
if((util.isArray(val))){
return val.length ? false : true;
}
if(util.isObject(val)){
return util.isEmptyObject(val);
}
return false;
};
//is a empty object
util.isEmptyObject=function(obj){
for(var name in obj){
return false;
}
return true;
};
//traverse object or array
util.each=function(object,callback){
var i=0,
len=object.length,
isObj = len === undefined ||util.isFunction(object);
if(isObj){
for(var name in object){
if(callback.call(object[name],name,object[name]) === false){
break;
}
}
}else{
for(;i<len;){
if(callback.call(object[i],i,object[i++]) === false){
break;
}
};
}
};
//class2type object
util.each("Boolean,Number,String,Function,Array,Date,RegExp,Object".split(","), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
//get object all key,composed of an array
util.keys=Object.keys||function(o){
var ret=[];
for (var p in o) {
if (o.hasOwnProperty(p)) {
ret.push(p)
}
}
return ret
};
//Remove an array of the same
util.unique=function(arr){
var o={};
util.each(arr,function(i,v){
o[v]=1;
});
return util.keys(o);
};
util.isInArray=function(arr,val){
if(!util.isArray(arr)){
return false;
}
var i=0,
len=arr.length;
for(;i<len;i++){
if(arr[i] === val){
return true;
}
}
return false;
};
//get the dependencies
util.parseDependencies=function(code){
code=code.replace(REGX.COMMENT,'');//empty comment
var ret = [], match,
reg=REGX.REQUIRE;
reg.lastIndex=0;
while(match = reg.exec(code)){
if(match[2]){
ret.push(match[2]);
}
}
return util.unique(ret);
};
// path to name
util.path2name=function(id){
if(util.isArray(id)){
var arr=[];
util.each(id,function(i,v){
var v=util.path2name(v);
arr.push(v);
});
return arr;
}
var reg=REGX.MODULENAME,
ret=reg.exec(id);
if(ret&& ret.length > 1){
id=ret[1].replace(REGX.JSSUFFIX,'');
}
return id;
};
})(module.util);
//path
(function(path){
//to dir name
path.dirname=function(uri){
var s = uri.match(REGX.BASEDIR);
return (s ? s[0] : '.') + '/';
};
//to real path
path.realpath=function(uri){
var base=module.options.base;
//absolute
if(!(uri.indexOf('//') > -1)){
uri=base+uri;
}
if(REGX.SLASHDIR.test(uri)){
uri=uri.replace(REGX.SLASHDIR,'');
}
if(!REGX.JSSUFFIX.test(uri)){
uri=uri+'.js';
}
return uri;
};
})(module.path);
//config base
(function(config){
var $path=module.path,
$config=module.options;
var base=$path.dirname(startPath);
$config.base=base;
})(module.options);
//module global variable or cache,when debug mode opening
var ModulesSet={};//module set
var ModuleCachesQueue=[];//[{id:id,dependencies:[],factory:function,links:[]},{}]
var StatusCacheQueue={};//{id:{status:0}}
//module method
(function(){
var $config=module.options,
$util=module.util,
$path=module.path;
/*
* @private
* @desc
replace placeholders({modules},{plugins},{mobile},{pad} and {web}) for actual directory
*
* @param {String} alias placeholder directory
* @return {String} alias actual directory
*
*/
module.dirs=function(alias){
alias=$util.isObject(alias) ? alias : {};
var dirs=$config.dirs,
reg=REGX['PLACEHOLDER_DIR'];
for(var dir in alias){
var ret=reg.exec(alias[dir]),
res=alias[dir];
if(ret&& ret.length > 1){
var r=dirs[ret[1]]||ret[1]||'';
res=res.replace(ret[0],r);
}
alias[dir]=res;
}
return alias;
};
/*
* @public
* @desc module initialization,module config
*
* @param {Object} conf,reeference module.options
seting module.options,
whether open require mode,
whether open debug mode
*/
module.init=function(conf){
conf=$util.isObject(conf) ? conf : {};
$config=$util.extend($config,conf);
//replace placeholder
$config.alias=module.dirs($config.alias);
if($config.require === true){
//require
global.require=module.declare;
//define
global.define=module.declare;
//define.remove
global.define.remove=module.remove;
}
if($config.debug === true){
module.ModulesSet=ModulesSet;
module.ModuleCachesQueue=ModuleCachesQueue;
module.StatusCacheQueue=StatusCacheQueue;
global.module=module;
global.module.config=module.init;
}
};
/*
* @method
* @public
* @desc
setting module alias
*
* @param {Object}
*/
module.alias=function(alias){
if($util.isEmpty(alias)){
return $config.alias;
}
alias=$util.isObject(alias) ? alias : {};
alias=module.dirs(alias);
$config.alias=$util.extend(alias,$config.alias);
};
/*
* @method
* @public
* @desc
setting module files,in the files,said the file is not module,only a common file
* @param {String/Array/Object}
String:a file name
Array:many file name
Object:a or many file,and the file name will be in the module.alias
*/
module.files=function(files){
if($util.isEmpty(files)){
return $config.files;
}
if($util.isString(files)){
files=[].concat(files);
}
if($util.isObject(files)){
var arr=[];
$util.each(files,function(k,v){
arr.push(k);
});
module.alias(files);
files=arr;
}
$config.files=$util.unique($config.files.concat(files));
};
/*
* @method
* @public
* @desc
global variables
according to such as jquery,zepto,jqmobi $ variable
*
*/
module.globals=function(globals){
if($util.isEmpty(globals)){
return $config.globals;
}
if($util.isString(globals)){
return $config.globals[globals]||'';
}
globals=$util.isObject(globals) ? globals : {};
$config.globals=$util.extend(globals,$config.globals);
};
/*
* @method
* @public
* @desc
module configuration,module init configuration
* @param {undefined/String/Object} name:
undefined:if name is empty,null,undefined,return all module configurations
String:conf is undefined,get module configuration
Object set many module configurations,{name:{configuration}}
* @param {undefine/Object} conf
undefined:name is not empty,null,undefined and so on,get a module configuration
Object set a module configuration
*/
module.sets=function(name,conf){
if($util.isEmpty(name)){
return $config.sets;
}
if($util.isObject(name)){
for(var i in name){
module.sets(i,name[i]);
}
return;
}
name=module.aliasId(name);
if(conf === undefined){
return $config.sets[name]||{};
}
conf=$util.isObject(conf) ? conf : {};
$config.sets[name]=$config.sets[name]||{};
$config.sets[name]=$util.extend(conf,$config.sets[name]);
};
//get all scripts
module.scripts=function(){
return document.getElementsByTagName('script');
};
//create script
module.createScript=function(name,async){
async=async===undefined || async ? true : false;
var node=document.createElement('script');
node.setAttribute('data-requiremodule',name);
node.type='text/javascript';
node.charset='utf-8';
node.async=async;
return node;
};
// get script data
module.getScriptData=function(evt){
var node = evt.currentTarget || evt.srcElement;
if(node.detachEvent){
node&&node.detachEvent('onreadystatechange',module.onScriptLoad);
node&&node.detachEvent('error',module.onScriptError);
}else{
node&&node.removeEventListener('load',module.onScriptLoad,false);
node&&node.removeEventListener('error',module.onScriptError,false);
}
return{
node:node,
id:node&&node.getAttribute('data-requiremodule')
};
};
//load javascript
module.loadJS=function(id){
var m=module.isInComs(id);
id=m !== null ? m : id;
if(module.getStatus(id) > STATUS.BEGIN){
return;
}
module.statusSet(id,STATUS.LOADING);
var head=document.getElementsByTagName('head')[0],
node=module.createScript(id),
id=module.aliasId(id,'v');
node.src = $path.realpath(id);
head.appendChild(node);
if(node.attachEvent){
node.attachEvent('onreadystatechange',module.onScriptLoad);
node.attachEvent('onerror',module.onScriptError);
}else{
node.addEventListener('load',module.onScriptLoad,false);
node.addEventListener('error',module.onScriptError,false);
}
};
//remove javascript by the data-requiremodule attribute
module.removeJS=function(name){
name=module.aliasId(name);
$util.each(module.scripts(),function(i,scriptNode) {
if (scriptNode&&scriptNode.getAttribute('data-requiremodule') === name) {
scriptNode.parentNode.removeChild(scriptNode);
return true;
}
});
};
//script load success callback
module.onScriptLoad=function(evt){
var el=evt.currentTarget || evt.srcElement;
if(evt.type === 'load' || (evt.type == 'readystatechange' && (el.readyState === 'loaded' || el.readyState === 'complete'))){
var data=module.getScriptData(evt),
id=data['id'];
module.statusSet(id,STATUS.LOADED);
if(module.isInFiles(id)){
module.compile(id);
}
//module.removeJS(id);
}
};
//script load error callback
module.onScriptError=function(evt){
var data=module.getScriptData(evt),
id=data['id'];
module.statusSet(id,STATUS.ERROR);
module.compile(id);
module.removeJS(id);
};
// set module status
module.statusSet=function(id,status){
id=module.aliasId(id);
if(!StatusCacheQueue[id]){
StatusCacheQueue[id]={};
}
StatusCacheQueue[id]['status']=status;
};
// get module status
module.getStatus=function(id){
id=module.aliasId(id);
return StatusCacheQueue[id]&&StatusCacheQueue[id]['status']||STATUS.BEGIN;
};
//load module
module.load=function(uris){
$util.each(uris,function(i,id){
module.loadJS(id);
});
};
// is module in the module.alias
module.isInAlias=function(name){
var alias=$config.alias;
for(var k in alias){
var v=$util.path2name(alias[k]);
if(k === name || v === name || alias[k] === name){
return {k:k,v:alias[k]};
}
}
return null;
};
//get alias id
module.aliasId=function(id,type){
type=type||'k';
var aid=module.isInAlias(id);
id=aid&&aid[type]||id;
return id;
};
//is module in the module.files
module.isInFiles=function(name){
var files=$config.files,
name=module.aliasId(name);
var i=0,
len=files.length;
for(;i<len;i++){
if(files[i] === name){
return true;
}
}
return false;
};
// is module in the module.coms
module.isInComs=function(name){
var coms=$config.coms,
k=module.aliasId(name),
v=module.aliasId(name,'v');
for(var m in coms){
if(k === m || $util.isInArray(coms[m],k) || $util.isInArray(coms[m],v)){
return m;
}
}
return null;
};
//is module already in the module set
module.isInModules=function(id){
id=module.aliasId(id);
return ModulesSet[id];
};
//separating a module which has not been in the module set
module.noInModulesItems=function(dependencies){
var arr=[];
$util.each(dependencies,function(i,id){
if(!module.isInModules(id)){
arr.push(id);
}
});
return arr;
};
/*
* @private
* @desc
is require a module, not define a module
such as
module.declare(id,dependencies,function(){})
module.declare(id,dependencies,function(require){})
return true
such as
module.declare(id,dependencies,function(require,exports){})
module.declare(id,dependencies,function(require,exports,module){})
return false
*
*/
module.isRequire=function(code){
if(code){
return REGX.REQUIRE_FUN.test(code);
}
return false;
};
//set module
module.moduleSet=function(id,dependencies,factory){
id=module.aliasId(id);
if(module.isInModules(id) && $util.isFunction(factory)){
if(module.isRequire(factory.toString())){
factory(this.declare);
return;
}
throw 'module \"'+ id + '\" already defined!';
}
if(!$util.isFunction(factory)){
return;
}
ModulesSet[id]={
id:id,
dependencies:dependencies,
factory:factory
};
};
//compile module
module.compile=function(id){
id=module.aliasId(id),
v=module.aliasId(id,'v');
$util.each(ModuleCachesQueue,function(index,json){
if(!json){
return;
}
var links=json['links']||[];
if(!($util.isInArray(links,id) || $util.isInArray(links,v))){
return;
}
function deleteLink(){
var i=0,
len=links.length;
for(;i<len;i++){
if(links[i] === id){
links.splice(i,1);
module.compile(id);
return;
}
}
};
if(links.length <= 1){
var uid=json['id']||$util.uid(),
dependencies=json['dependencies']||[],
factory=json['factory']||'';
var ms=ModulesSet[id]||{},
dept=ms['dependencies']||[];
dependencies=dependencies.concat(dept);
dependencies=$util.unique(dependencies);
ModuleCachesQueue.splice(index,1);
module.complete(uid,dependencies,factory);
}
//delete loaded dependency
deleteLink();
});
};
//complete a module,return exports
module.complete=function(id,dependencies,factory){
module.moduleSet(id,dependencies,factory);
var exports=module.exports(id);
module.compile(id);
return exports;
};
//buile a module
module.build=function(module){
var factory=module.factory;
module.exports={};
delete module.factory;
var moduleExports=factory(this.declare,module.exports,module);
//jQuery direct return
if($util.isEmptyObject(module.exports)){
module.exports=moduleExports||{};
}
return module.exports;
};
//module's exports
module.exports=function(id){
//module in ModulesSet
if(module.isInModules(id)){
id=module.aliasId(id);
var exports=ModulesSet[id].factory ? module.build(ModulesSet[id]) : ModulesSet[id].exports;
return exports;
}
return null;
};
/*
* @method
* @public
* @desc
the main method,define or require a module
*
* @param {String} id : module id,not necessary
* @param {Array} dependencies : the module dependencies,necessary
* @param {Function} : a callback or module factory,is necessary
*
* @return
return a exports or null,when asynchronous loading return null,require a module return module.exports
*/
module.declare=function(id,dependencies,factory){
dependencies=dependencies||[];
if($util.isArray(id)){
factory=dependencies;
dependencies=id;
id='';
}
if($util.isFunction(dependencies)){
factory=dependencies;
dependencies=[];
}
if($util.isFunction(id)){
factory=id;
dependencies=$util.parseDependencies(factory.toString())||[];
id='';
}
//dependencies=id ? [].concat(id).concat(dependencies) : dependencies;
//anonymous module
id=id||$util.uid();
var items=module.noInModulesItems(dependencies);
if(items&&items.length){
var json={
id:id,
dependencies:dependencies,
factory:factory,
links:$util.path2name(dependencies)
};
ModuleCachesQueue.push(json);
module.load(dependencies);
return;
}
return module.complete(id,dependencies,factory);
};
//remove a module,only in open require mode
module.remove=function(id){
id=module.aliasId(id);
//remove javascript
module.removeJS(id);
//delete status
delete StatusCacheQueue[id];
//delete module
delete ModulesSet[id];
};
})();
//global method
global.module=global.module||{};
global.module.config=module.init;
global.module.alias=module.alias;
global.module.files=module.files;
global.module.globals=module.globals;
global.module.sets=module.sets;
global.module.declare=module.declare;
})(this); | module.js | /*
* @version v.1.1.123.0
* @name Plugins Modules
* @author donghanji
* @datetime 2013-01-07
*
* @desc
//The aims of PM is that taking modules as the core to form a powerful plug-in library.
//This file is the core of PM,Modules.
//This is the first version of PM.
//The future of the PM, you and I, we us grow together...
*
*/
;(function(global,undefined){
//location pathname
var startPath = window.location.pathname,
//private property
class2type={},
toString=Object.prototype.toString;
//module object
var module={
version:'1.1.123.0',//version
options:{
'require':false,//whether open require mode
'timeout':7000,//.ms
'base':'',//base path
'dirs':{},//directories,include modules,plugins,mobile,pad,web
'alias':{},//module alias
'files':[],//not a module,a common file,there is no define method in it
'globals':{},//global variables
'sets':{},//module configuration
'coms':{},//one file ,multiple modules
'debug':false//whether open debug mode
},
util:{},
path:{}
};
//regx
var REGX={
'SLASHDIR':/^\//,
'BASEDIR':/.*(?=\/.*$)/,
'JSSUFFIX':/\.js$/,
'COMMENT':/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
'REQUIRE':/(?:^|[^.$])\brequire\s*\(\s*(["'])([^"'\s\)]+)\1\s*\)/g,
'REQUIRE_FUN':/^function \(\w*\)/,
'MODULENAME':/\/([\w.]+)?(?:\1)?$/,
'PLACEHOLDER_DIR':/\{(\S+)?\}(?:\1)?/
},
//status
STATUS={
'ERROR':-1,
'BEGIN':0,
'LOADING':1,
'LOADED':2,
'END':3
};
/*
* @anme util
* @desc
the private utilities,internal use only.
*
*/
(function(util){
util.extend=function(){
var options,
target=arguments[0]||{},
length=arguments.length,
i=1;
if(length === i){
target=this;
--i;
}
for(;i<length;i++){
options=arguments[i];
if(typeof options === 'object'){
for(var name in options){
target[name]=options[name];
}
}
}
return target;
};
//is* method,element attribute is *
util.extend({
type:function(value){
return value == null ?
String(value) :
class2type[toString.call(value)] || 'object';
},
isNumeric:function(value){
return !isNaN(parseFloat(value)) && isFinite(value);
},
isString:function(value){
return util.type(value) === 'string';
},
isFunction:function(value){
return util.type(value) === 'function';
},
isObject:function(value){
return util.type(value) === 'object';
},
isArray:function(value){
return util.type(value) === 'array';
}
});
//now time
util.now=function(){
return new Date().getTime();
};
//unique id
util.uid=function(){
return new Date().getTime()+Math.floor(Math.random()*1000000);
};
//is empty
util.isEmpty=function(val){
if(val === '' || val === undefined || val === null){
return true;
}
if((util.isArray(val))){
return val.length ? false : true;
}
if(util.isObject(val)){
return util.isEmptyObject(val);
}
return false;
};
//is a empty object
util.isEmptyObject=function(obj){
for(var name in obj){
return false;
}
return true;
};
//traverse object or array
util.each=function(object,callback){
var i=0,
len=object.length,
isObj = len === undefined ||util.isFunction(object);
if(isObj){
for(var name in object){
if(callback.call(object[name],name,object[name]) === false){
break;
}
}
}else{
for(;i<len;){
if(callback.call(object[i],i,object[i++]) === false){
break;
}
};
}
};
//class2type object
util.each("Boolean,Number,String,Function,Array,Date,RegExp,Object".split(","), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
//get object all key,composed of an array
util.keys=Object.keys||function(o){
var ret=[];
for (var p in o) {
if (o.hasOwnProperty(p)) {
ret.push(p)
}
}
return ret
};
//Remove an array of the same
util.unique=function(arr){
var o={};
util.each(arr,function(i,v){
o[v]=1;
});
return util.keys(o);
};
util.isInArray=function(arr,val){
if(!util.isArray(arr)){
return false;
}
var i=0,
len=arr.length;
for(;i<len;i++){
if(arr[i] === val){
return true;
}
}
return false;
};
//get the dependencies
util.parseDependencies=function(code){
code=code.replace(REGX.COMMENT,'');//empty comment
var ret = [], match,
reg=REGX.REQUIRE;
reg.lastIndex=0;
while(match = reg.exec(code)){
if(match[2]){
ret.push(match[2]);
}
}
return util.unique(ret);
};
// path to name
util.path2name=function(id){
if(util.isArray(id)){
var arr=[];
util.each(id,function(i,v){
var v=util.path2name(v);
arr.push(v);
});
return arr;
}
var reg=REGX.MODULENAME,
ret=reg.exec(id);
if(ret&& ret.length > 1){
id=ret[1].replace(REGX.JSSUFFIX,'');
}
return id;
};
})(module.util);
//path
(function(path){
//to dir name
path.dirname=function(uri){
var s = uri.match(REGX.BASEDIR);
return (s ? s[0] : '.') + '/';
};
//to real path
path.realpath=function(uri){
var base=module.options.base;
//absolute
if(!(uri.indexOf('//') > -1)){
uri=base+uri;
}
if(REGX.SLASHDIR.test(uri)){
uri=uri.replace(REGX.SLASHDIR,'');
}
if(!REGX.JSSUFFIX.test(uri)){
uri=uri+'.js';
}
return uri;
};
})(module.path);
//config base
(function(config){
var $path=module.path,
$config=module.options;
var base=$path.dirname(startPath);
$config.base=base;
})(module.options);
//module global variable or cache,when debug mode opening
var ModulesSet={};//module set
var ModuleCachesQueue=[];//[{id:id,dependencies:[],factory:function,links:[]},{}]
var StatusCacheQueue={};//{id:{status:0}}
//module method
(function(){
var $config=module.options,
$util=module.util,
$path=module.path;
/*
* @private
* @desc
replace placeholders({modules},{plugins},{mobile},{pad} and {web}) for actual directory
*
* @param {String} alias placeholder directory
* @return {String} alias actual directory
*
*/
module.dirs=function(alias){
alias=$util.isObject(alias) ? alias : {};
var dirs=$config.dirs,
reg=REGX['PLACEHOLDER_DIR'];
for(var dir in alias){
var ret=reg.exec(alias[dir]),
res=alias[dir];
if(ret&& ret.length > 1){
var r=dirs[ret[1]]||'';
res=res.replace(ret[0],r);
}
alias[dir]=res;
}
return alias;
};
/*
* @public
* @desc module initialization,module config
*
* @param {Object} conf,reeference module.options
seting module.options,
whether open require mode,
whether open debug mode
*/
module.init=function(conf){
conf=$util.isObject(conf) ? conf : {};
$config=$util.extend($config,conf);
//replace placeholder
$config.alias=module.dirs($config.alias);
if($config.require === true){
//require
global.require=module.declare;
//define
global.define=module.declare;
//define.remove
global.define.remove=module.remove;
}
if($config.debug === true){
module.ModulesSet=ModulesSet;
module.ModuleCachesQueue=ModuleCachesQueue;
module.StatusCacheQueue=StatusCacheQueue;
global.module=module;
global.module.config=module.init;
}
};
/*
* @method
* @public
* @desc
setting module alias
*
* @param {Object}
*/
module.alias=function(alias){
if($util.isEmpty(alias)){
return $config.alias;
}
alias=$util.isObject(alias) ? alias : {};
alias=module.dirs(alias);
$config.alias=$util.extend(alias,$config.alias);
};
/*
* @method
* @public
* @desc
setting module files,in the files,said the file is not module,only a common file
* @param {String/Array/Object}
String:a file name
Array:many file name
Object:a or many file,and the file name will be in the module.alias
*/
module.files=function(files){
if($util.isEmpty(files)){
return $config.files;
}
if($util.isString(files)){
files=[].concat(files);
}
if($util.isObject(files)){
var arr=[];
$util.each(files,function(k,v){
arr.push(k);
});
module.alias(files);
files=arr;
}
$config.files=$util.unique($config.files.concat(files));
};
/*
* @method
* @public
* @desc
global variables
according to such as jquery,zepto,jqmobi $ variable
*
*/
module.globals=function(globals){
if($util.isEmpty(globals)){
return $config.globals;
}
if($util.isString(globals)){
return $config.globals[globals]||'';
}
globals=$util.isObject(globals) ? globals : {};
$config.globals=$util.extend(globals,$config.globals);
};
/*
* @method
* @public
* @desc
module configuration,module init configuration
* @param {undefined/String/Object} name:
undefined:if name is empty,null,undefined,return all module configurations
String:conf is undefined,get module configuration
Object set many module configurations,{name:{configuration}}
* @param {undefine/Object} conf
undefined:name is not empty,null,undefined and so on,get a module configuration
Object set a module configuration
*/
module.sets=function(name,conf){
if($util.isEmpty(name)){
return $config.sets;
}
if($util.isObject(name)){
for(var i in name){
module.sets(i,name[i]);
}
return;
}
name=module.aliasId(name);
if(conf === undefined){
return $config.sets[name]||{};
}
conf=$util.isObject(conf) ? conf : {};
$config.sets[name]=$config.sets[name]||{};
$config.sets[name]=$util.extend(conf,$config.sets[name]);
};
//get all scripts
module.scripts=function(){
return document.getElementsByTagName('script');
};
//create script
module.createScript=function(name,async){
async=async===undefined || async ? true : false;
var node=document.createElement('script');
node.setAttribute('data-requiremodule',name);
node.type='text/javascript';
node.charset='utf-8';
node.async=async;
return node;
};
// get script data
module.getScriptData=function(evt){
var node = evt.currentTarget || evt.srcElement;
if(node.detachEvent){
node&&node.detachEvent('onreadystatechange',module.onScriptLoad);
node&&node.detachEvent('error',module.onScriptError);
}else{
node&&node.removeEventListener('load',module.onScriptLoad,false);
node&&node.removeEventListener('error',module.onScriptError,false);
}
return{
node:node,
id:node&&node.getAttribute('data-requiremodule')
};
};
//load javascript
module.loadJS=function(id){
var m=module.isInComs(id);
id=m !== null ? m : id;
if(module.getStatus(id) > STATUS.BEGIN){
return;
}
module.statusSet(id,STATUS.LOADING);
var head=document.getElementsByTagName('head')[0],
node=module.createScript(id),
id=module.aliasId(id,'v');
node.src = $path.realpath(id);
head.appendChild(node);
if(node.attachEvent){
node.attachEvent('onreadystatechange',module.onScriptLoad);
node.attachEvent('onerror',module.onScriptError);
}else{
node.addEventListener('load',module.onScriptLoad,false);
node.addEventListener('error',module.onScriptError,false);
}
};
//remove javascript by the data-requiremodule attribute
module.removeJS=function(name){
name=module.aliasId(name);
$util.each(module.scripts(),function(i,scriptNode) {
if (scriptNode&&scriptNode.getAttribute('data-requiremodule') === name) {
scriptNode.parentNode.removeChild(scriptNode);
return true;
}
});
};
//script load success callback
module.onScriptLoad=function(evt){
var el=evt.currentTarget || evt.srcElement;
if(evt.type === 'load' || (evt.type == 'readystatechange' && (el.readyState === 'loaded' || el.readyState === 'complete'))){
var data=module.getScriptData(evt),
id=data['id'];
module.statusSet(id,STATUS.LOADED);
if(module.isInFiles(id)){
module.compile(id);
}
//module.removeJS(id);
}
};
//script load error callback
module.onScriptError=function(evt){
var data=module.getScriptData(evt),
id=data['id'];
module.statusSet(id,STATUS.ERROR);
module.compile(id);
module.removeJS(id);
};
// set module status
module.statusSet=function(id,status){
id=module.aliasId(id);
if(!StatusCacheQueue[id]){
StatusCacheQueue[id]={};
}
StatusCacheQueue[id]['status']=status;
};
// get module status
module.getStatus=function(id){
id=module.aliasId(id);
return StatusCacheQueue[id]&&StatusCacheQueue[id]['status']||STATUS.BEGIN;
};
//load module
module.load=function(uris){
$util.each(uris,function(i,id){
module.loadJS(id);
});
};
// is module in the module.alias
module.isInAlias=function(name){
var alias=$config.alias;
for(var k in alias){
var v=$util.path2name(alias[k]);
if(k === name || v === name || alias[k] === name){
return {k:k,v:alias[k]};
}
}
return null;
};
//get alias id
module.aliasId=function(id,type){
type=type||'k';
var aid=module.isInAlias(id);
id=aid&&aid[type]||id;
return id;
};
//is module in the module.files
module.isInFiles=function(name){
var files=$config.files,
name=module.aliasId(name);
var i=0,
len=files.length;
for(;i<len;i++){
if(files[i] === name){
return true;
}
}
return false;
};
// is module in the module.coms
module.isInComs=function(name){
var coms=$config.coms,
k=module.aliasId(name),
v=module.aliasId(name,'v');
for(var m in coms){
if(k === m || $util.isInArray(coms[m],k) || $util.isInArray(coms[m],v)){
return m;
}
}
return null;
};
//is module already in the module set
module.isInModules=function(id){
id=module.aliasId(id);
return ModulesSet[id];
};
//separating a module which has not been in the module set
module.noInModulesItems=function(dependencies){
var arr=[];
$util.each(dependencies,function(i,id){
if(!module.isInModules(id)){
arr.push(id);
}
});
return arr;
};
/*
* @private
* @desc
is require a module, not define a module
such as
module.declare(id,dependencies,function(){})
module.declare(id,dependencies,function(require){})
return true
such as
module.declare(id,dependencies,function(require,exports){})
module.declare(id,dependencies,function(require,exports,module){})
return false
*
*/
module.isRequire=function(code){
if(code){
return REGX.REQUIRE_FUN.test(code);
}
return false;
};
//set module
module.moduleSet=function(id,dependencies,factory){
id=module.aliasId(id);
if(module.isInModules(id) && $util.isFunction(factory)){
if(module.isRequire(factory.toString())){
factory(this.declare);
return;
}
throw 'module \"'+ id + '\" already defined!';
}
if(!$util.isFunction(factory)){
return;
}
ModulesSet[id]={
id:id,
dependencies:dependencies,
factory:factory
};
};
//compile module
module.compile=function(id){
id=module.aliasId(id),
v=module.aliasId(id,'v');
$util.each(ModuleCachesQueue,function(index,json){
if(!json){
return;
}
var links=json['links']||[];
if(!($util.isInArray(links,id) || $util.isInArray(links,v))){
return;
}
function deleteLink(){
var i=0,
len=links.length;
for(;i<len;i++){
if(links[i] === id){
links.splice(i,1);
module.compile(id);
return;
}
}
};
if(links.length <= 1){
var uid=json['id']||$util.uid(),
dependencies=json['dependencies']||[],
factory=json['factory']||'';
var ms=ModulesSet[id]||{},
dept=ms['dependencies']||[];
dependencies=dependencies.concat(dept);
dependencies=$util.unique(dependencies);
ModuleCachesQueue.splice(index,1);
module.complete(uid,dependencies,factory);
}
//delete loaded dependency
deleteLink();
});
};
//complete a module,return exports
module.complete=function(id,dependencies,factory){
module.moduleSet(id,dependencies,factory);
var exports=module.exports(id);
module.compile(id);
return exports;
};
//buile a module
module.build=function(module){
var factory=module.factory;
module.exports={};
delete module.factory;
var moduleExports=factory(this.declare,module.exports,module);
//jQuery direct return
if($util.isEmptyObject(module.exports)){
module.exports=moduleExports||{};
}
return module.exports;
};
//module's exports
module.exports=function(id){
//module in ModulesSet
if(module.isInModules(id)){
id=module.aliasId(id);
var exports=ModulesSet[id].factory ? module.build(ModulesSet[id]) : ModulesSet[id].exports;
return exports;
}
return null;
};
/*
* @method
* @public
* @desc
the main method,define or require a module
*
* @param {String} id : module id,not necessary
* @param {Array} dependencies : the module dependencies,necessary
* @param {Function} : a callback or module factory,is necessary
*
* @return
return a exports or null,when asynchronous loading return null,require a module return module.exports
*/
module.declare=function(id,dependencies,factory){
dependencies=dependencies||[];
if($util.isArray(id)){
factory=dependencies;
dependencies=id;
id='';
}
if($util.isFunction(dependencies)){
factory=dependencies;
dependencies=[];
}
if($util.isFunction(id)){
factory=id;
dependencies=$util.parseDependencies(factory.toString())||[];
id='';
}
//dependencies=id ? [].concat(id).concat(dependencies) : dependencies;
//anonymous module
id=id||$util.uid();
var items=module.noInModulesItems(dependencies);
if(items&&items.length){
var json={
id:id,
dependencies:dependencies,
factory:factory,
links:$util.path2name(dependencies)
};
ModuleCachesQueue.push(json);
module.load(dependencies);
return;
}
return module.complete(id,dependencies,factory);
};
//remove a module,only in open require mode
module.remove=function(id){
id=module.aliasId(id);
//remove javascript
module.removeJS(id);
//delete status
delete StatusCacheQueue[id];
//delete module
delete ModulesSet[id];
};
})();
//global method
global.module=global.module||{};
global.module.config=module.init;
global.module.alias=module.alias;
global.module.files=module.files;
global.module.globals=module.globals;
global.module.sets=module.sets;
global.module.declare=module.declare;
})(this); | 优化处理module.dirs方法,使其原有设置如module.dirs({libs:'libs'}),即KV值相同的时候,可以不用在dirs中进行设置,可直接使用。
| module.js | 优化处理module.dirs方法,使其原有设置如module.dirs({libs:'libs'}),即KV值相同的时候,可以不用在dirs中进行设置,可直接使用。 | <ide><path>odule.js
<ide> var ret=reg.exec(alias[dir]),
<ide> res=alias[dir];
<ide> if(ret&& ret.length > 1){
<del> var r=dirs[ret[1]]||'';
<add> var r=dirs[ret[1]]||ret[1]||'';
<ide> res=res.replace(ret[0],r);
<ide> }
<ide> |
|
JavaScript | apache-2.0 | e58c4cfe1cc08ad4b59aa8965753b50f32cbd9f7 | 0 | jbigos/LandSharkSwimAnalysis,jbigos/LandSharkSwimAnalysis | /*!
* Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// jQuery to collapse the navbar on scroll
function collapseNavbar() {
if ($(".navbar").offset().top > 50) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
}
$(window).scroll(collapseNavbar);
$(document).ready(collapseNavbar);
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('a.page-scroll').bind('click', function(event) {
console.log("When am I scrolling");
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$(".navbar-collapse").collapse('hide');
});
var grps;
var atts;
require([
"esri/map",
"esri/layers/FeatureLayer",
"esri/tasks/QueryTask",
"esri/tasks/query",
"esri/arcgis/utils",
"dojo/dom",
"dojo/dom-construct",
"dojo/on",
"dojo/parser",
"dojo/_base/lang",
"Plotly/plotly-latest.min",
"moment/moment",
"dojo/domReady!"
],
function(
Map,
FeatureLayer,
QueryTask,
Query,
arcgisutils,
dom,domConstruct,
on,parser,lang,plt,moment
) {
parser.parse();
var ageGrpby;
//format
String.format = function() {
// The string containing the format items (e.g. "{0}")
// will and always has to be the first argument.
var theString = arguments[0];
// start with the second argument (i = 1)
for (var i = 1; i < arguments.length; i++) {
// "gm" = RegEx options for Global search (more than one instance)
// and for Multiline search
var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
theString = theString.replace(regEx, arguments[i]);
}
return theString;
};
/*var map = new Map("map", {
basemap: "gray",
center:[-79.792369,41.765298],
zoom: 6
});*/
var _1mmap = new Map("courseMap", {
basemap: "satellite",
center:[-70.939625,42.860688],
zoom: 16
});
var _halfmmap = new Map("halfcourseMap", {
basemap: "satellite",
center:[-70.939625,42.860688],
zoom: 16
});
//Query to get the attributes
var q = new Query();
q.where = "1=1";
q.outFields = ["*"];
var qt = new QueryTask("https://services7.arcgis.com/Gk8wYdLBgQPxqVZU/arcgis/rest/services/LandSharkResults/FeatureServer/0");
qt.on("complete",processData);
qt.execute(q);
var fLayer = new FeatureLayer("https://services7.arcgis.com/Gk8wYdLBgQPxqVZU/arcgis/rest/services/LandSharkResults/FeatureServer/0",{
outFields:["*"],
id:'swim'
});
//map.addLayer(fLayer);
arcgisutils.createMap("a56c8aa0b35442d49b2ecb89ffb834e7","map");
//atts = [];
//on(dom.byId("btnC"), "click", function()
var prpgrnRange = plt.d3.interpolateRgb('#40004b', '#00441b');
var clrs;
plt.d3.json("colorbrewer.json",function(clr){
console.log(clr)
clrs = clr;
});
processes = false;
//fLayer.on("graphic-draw",function(grt)
function processData(qRes)
{
/*
if (atts.length < 133) {
atts.push(grt.graphic.attributes)
}
if (atts.length == 133) {
console.log(atts.length)*/
var dt = moment('It is 2012-05-25', 'YYYY-MM-DD');
console.log(dt)
/*
fLyr = map.getLayer('swim');
console.log(fLyr);
grps = fLyr.graphics*/
/* grps.forEach(function (g) {
atts.push(g.attributes)
})*/
atts = _.pluck(qRes.featureSet.features,"attributes")
var eventgrpby = _.groupBy(atts, 'Event')
//Charts for the Half mile
var _halfmdivGrp = _.groupBy(eventgrpby["Half"], 'Div')
console.log(_halfmdivGrp);
//Get the top times and Competitors
var halfTime = _.chain(eventgrpby.Half).flatten(true).pluck("Time").sortBy().value();
var halfTopTime = halfTime[0]
domConstruct.place(lang.replace("<tr><td>#Swimmers</td><td>{text}</td></tr><tr><td>Top Time</td><td>{tTime}</td></tr>", {
text: halfTime.length.toString(),
tTime: halfTopTime
}), dom.byId("tBod"));
var res = [];
var labels = [];
var boxPlotColor = {};
_.each(_halfmdivGrp, function (elem, ind, list) {
//var obj = {}
//obj[ind] = elem.length;
//res.push(obj)
//var darray = [ind,elem.length]
labels.push(ind)
res.push(elem.length);
var clrNum = (Math.random() * 4)
boxPlotColor[ind] = prpgrnRange(clrNum);
})
//clrs["PRGn"][res.length]
var data = [{
values: res,
labels: labels,
type: "pie",
marker: {
colors: clrs["Paired"][res.length]
}
}];
var layout = {
height: 400,
width: 500,
paper_bgcolor: "darkgray",
plot_bgcolor: "darkgray"
};
//Map the colors to a lookup
lookup = _.object(labels, data[0].marker.colors)
plt.newPlot("_HalfPieChart", data, layout, {displayModeBar: false});
//Boxplots
barHalfMDataChart = []
_.each(_halfmdivGrp, function (e, i, l) {
barHalfMData = {}
var tData = []
var ts = _.pluck(_halfmdivGrp[i], 'Time')
d1 = moment(ts[0], "mm:ss:SS")
_.each(ts, function (vals) {
d2 = moment(vals, "mm:ss:SS")
tmDiff = d2.diff(d1, "minutes")
tData.push(tmDiff);
})
barHalfMData["x"] = tData;
barHalfMData["type"] = "box";
barHalfMData["name"] = i;
barHalfMData["boxpoints"] = "all";
barHalfMData["marker"] = {color: lookup[i]};//{"outliercolor": clrs["PRGn"][e.length][4].toString()};
barHalfMDataChart.push(barHalfMData);
});
plt.newPlot("_HalfBoxPlot", barHalfMDataChart, {
paper_bgcolor: "darkgray",
plot_bgcolor: "darkgray"
});//, layout);
//end charts for the half
//Charts for the 1 mile
var _1mdivGrp = _.groupBy(eventgrpby["Mile"], 'Div')
console.log(_1mdivGrp);
//Get the top times and Competitors
var mileTime = _.chain(eventgrpby.Mile).flatten(true).pluck("Time").sortBy().value();
var mileTopTime = mileTime[0]
domConstruct.place(lang.replace("<tr><td>#Swimmers</td><td>{text}</td></tr><tr><td>Top Time</td><td>{tTime}</td></tr>", {
text: mileTime.length.toString(),
tTime: mileTopTime
}), dom.byId("tMileBod"));
var res = [];
var labels = [];
_.each(_1mdivGrp, function (elem, ind, list) {
//var obj = {}
//obj[ind] = elem.length;
//res.push(obj)
//var darray = [ind,elem.length]
labels.push(ind)
res.push(elem.length);
})
var data = [{
values: res,
labels: labels,
type: 'pie',
marker: {
colors: clrs["Paired"][res.length]
}
}];
var layout = {
height: 400,
width: 500,
paper_bgcolor: "darkgray",
plot_bgcolor: "darkgray"
};
//Map the colors to a lookup
lookup = _.object(labels, data[0].marker.colors)
plt.newPlot('_1MPieChart', data, layout, {displayModeBar: false});
//Boxplots
bar1MDataChart = []
_.each(_1mdivGrp, function (e, i, l) {
bar1MData = {}
var tData = []
var ts = _.pluck(_1mdivGrp[i], 'Time')
d1 = moment(ts[0], "mm:ss:SS")
_.each(ts, function (vals) {
d2 = moment(vals, "mm:ss:SS")
tmDiff = d2.diff(d1, "minutes")
tData.push(tmDiff)
})
bar1MData["x"] = tData;
bar1MData["type"] = 'box';
bar1MData["name"] = i;
bar1MData["boxpoints"] = 'all';
bar1MData["marker"] = {color: lookup[i]};
bar1MDataChart.push(bar1MData);
});
plt.newPlot('_1MBoxPlot', bar1MDataChart, {
paper_bgcolor: "darkgray",
plot_bgcolor: "darkgray"
})//, layout);
//end 1 mile charts
//Charts for the 2 mile
var _2mdivGrp = _.groupBy(eventgrpby["2Mile"], 'Div')
//Get the top times and Competitors
var twomileTime = _.chain(eventgrpby["2Mile"]).flatten(true).pluck("Time").sortBy().value();
var twomileModTime = []
twomileTime.forEach(function (t) {
if (t.charAt(0) == "1") {
twomileModTime.push(moment(t.replace(t, t + ":00"), "h:mm:ss:SS"))
}
else if (t.charAt(0) != "1") {
twomileModTime.push(moment("00:" + t, "h:mm:ss:SS"))
}
})
var twomileTopTime = moment.min(twomileModTime)
domConstruct.place(lang.replace("<tr><td>#Swimmers</td><td>{text}</td></tr><tr><td>Top Time</td><td>{tTime}</td></tr>", {
text: twomileModTime.length.toString(),
tTime: twomileTopTime._i
}), dom.byId("tTwoMileBod"));
var _2mres = [];
var _2mlabels = [];
_.each(_2mdivGrp, function (elem, ind, list) {
//var obj = {}
//obj[ind] = elem.length;
//res.push(obj)
//var darray = [ind,elem.length]
_2mlabels.push(ind)
_2mres.push(elem.length);
})
var _2data = [{
values: _2mres,
labels: _2mlabels,
type: 'pie',
marker: {
colors: clrs["Paired"][res.length]
}
}];
var _2layout = {
height: 400,
width: 500,
paper_bgcolor: "darkgray",
plot_bgcolor: "darkgray"
};
var lookup = _.object(labels, data[0].marker.colors)
plt.newPlot('_2MPieChart', _2data, _2layout, {displayModeBar: false});
//Boxplots
bar2MDataChart = []
_.each(_2mdivGrp, function (e, i, l) {
bar2MData = {}
var _2tData = []
var _2mts = _.pluck(_2mdivGrp[i], 'Time')
_2md1 = moment(_2mts[0], "mm:ss:SS")
_.each(_2mts, function (_2mvals) {
if (_2mvals.charAt(0) == 1) {
_2md2 = moment(_2mvals, "h:mm:ss")
}
else {
var n_2mvals = "0:" + _2mvals
_2md2 = moment(n_2mvals, "h:mm:ss:SS")
}
_2mtmDiff = _2md2.diff(_2md1, "minutes")
_2tData.push(_2mtmDiff)
})
bar2MData["x"] = _2tData;
bar2MData["type"] = 'box';
bar2MData["name"] = i;
bar2MData["boxpoints"] = 'all';
bar2MData["marker"] = {color: lookup[i]};
bar2MDataChart.push(bar2MData);
});
plt.newPlot('_2MBoxPlot', bar2MDataChart, {paper_bgcolor: "darkgray", plot_bgcolor: "darkgray"})//, layout);
//end 2 mile charts
//end of else
};
/* fLayer.on("load",function(l){
console.log(l.layer.graphics);
})*/
//atts2 = []
/*fLayer.on("graphic-draw",function(grt){
if(atts2.length < 133) {
atts2.push(grt.graphic.attributes)
if (atts2.length ==133){
console.log(atts2.length)
}
}})*/
});
| js/grayscale.js | /*!
* Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// jQuery to collapse the navbar on scroll
function collapseNavbar() {
if ($(".navbar").offset().top > 50) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
}
$(window).scroll(collapseNavbar);
$(document).ready(collapseNavbar);
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$(".navbar-collapse").collapse('hide');
});
require(["esri/map","esri/layers/FeatureLayer",
"esri/renderers/HeatmapRenderer","moment/moment","Plotly/plotly-latest.min",
"dojo/domReady!"], function(Map,FeatureLayer,HeatmapRenderer,moment,plt) {
var map = new Map("map", {
center: [-71.046, 42.42],
zoom: 8,
basemap: "gray"
});
var heatmapRenderer = new HeatmapRenderer({
colors: ["rgba(0, 0, 255, 0)","rgb(0, 0, 255)","rgb(255, 0, 255)", "rgb(255, 0, 0)"]})
var lUrl = "http://services7.arcgis.com/k1gt6XMqKCsvSvjs/arcgis/rest/services/LandSharkResults/FeatureServer/0"
var resLayer = new FeatureLayer(lUrl,{
outFields:["*"],
id:'swim'
})
resLayer.setRenderer(heatmapRenderer);
map.addLayer(resLayer);
atts = [];
var grps = resLayer.graphics;
grps.forEach(function(g){
atts.push(g.attributes)
})
//Break the event data into the different waves
var eventgrpby = _.groupBy(atts,'Event');
//Charts for 1 mile
var _1mdivGrp = _.groupBy(eventgrpby["Mile"],'Div');
var res = [];
var labels = [];
_.each(_1mdivGrp,function(elem,ind,list){
labels.push(ind);
res.push(elem.length);
})
var data = [
{
values:res,
labels:labels,
type:'pie'
}
];
var layout = {
height: 400,
width:500
};
plt.newPlot('_1MPieChart',data,layout,{displayModeBar:false});
});
| replace grey.js
| js/grayscale.js | replace grey.js | <ide><path>s/grayscale.js
<ide> // jQuery for page scrolling feature - requires jQuery Easing plugin
<ide> $(function() {
<ide> $('a.page-scroll').bind('click', function(event) {
<add> console.log("When am I scrolling");
<ide> var $anchor = $(this);
<ide> $('html, body').stop().animate({
<ide> scrollTop: $($anchor.attr('href')).offset().top
<ide> $(".navbar-collapse").collapse('hide');
<ide> });
<ide>
<del>require(["esri/map","esri/layers/FeatureLayer",
<del>"esri/renderers/HeatmapRenderer","moment/moment","Plotly/plotly-latest.min",
<del> "dojo/domReady!"], function(Map,FeatureLayer,HeatmapRenderer,moment,plt) {
<del> var map = new Map("map", {
<del> center: [-71.046, 42.42],
<del> zoom: 8,
<del> basemap: "gray"
<del> });
<del>
<del> var heatmapRenderer = new HeatmapRenderer({
<del> colors: ["rgba(0, 0, 255, 0)","rgb(0, 0, 255)","rgb(255, 0, 255)", "rgb(255, 0, 0)"]})
<del>
<del> var lUrl = "http://services7.arcgis.com/k1gt6XMqKCsvSvjs/arcgis/rest/services/LandSharkResults/FeatureServer/0"
<del> var resLayer = new FeatureLayer(lUrl,{
<del> outFields:["*"],
<del> id:'swim'
<del>
<del> })
<del> resLayer.setRenderer(heatmapRenderer);
<del> map.addLayer(resLayer);
<del>
<del>
<del> atts = [];
<del>
<del> var grps = resLayer.graphics;
<del> grps.forEach(function(g){
<del> atts.push(g.attributes)
<del> })
<del>
<del> //Break the event data into the different waves
<del> var eventgrpby = _.groupBy(atts,'Event');
<del>
<del> //Charts for 1 mile
<del> var _1mdivGrp = _.groupBy(eventgrpby["Mile"],'Div');
<del>
<del> var res = [];
<del> var labels = [];
<del> _.each(_1mdivGrp,function(elem,ind,list){
<del> labels.push(ind);
<del> res.push(elem.length);
<del> })
<del>
<del> var data = [
<add>
<add>var grps;
<add>var atts;
<add>require([
<add> "esri/map",
<add> "esri/layers/FeatureLayer",
<add> "esri/tasks/QueryTask",
<add> "esri/tasks/query",
<add> "esri/arcgis/utils",
<add> "dojo/dom",
<add> "dojo/dom-construct",
<add> "dojo/on",
<add> "dojo/parser",
<add> "dojo/_base/lang",
<add> "Plotly/plotly-latest.min",
<add> "moment/moment",
<add> "dojo/domReady!"
<add> ],
<add> function(
<add> Map,
<add> FeatureLayer,
<add> QueryTask,
<add> Query,
<add> arcgisutils,
<add> dom,domConstruct,
<add> on,parser,lang,plt,moment
<add> ) {
<add>
<add> parser.parse();
<add> var ageGrpby;
<add>
<add>
<add> //format
<add> String.format = function() {
<add> // The string containing the format items (e.g. "{0}")
<add> // will and always has to be the first argument.
<add> var theString = arguments[0];
<add>
<add> // start with the second argument (i = 1)
<add> for (var i = 1; i < arguments.length; i++) {
<add> // "gm" = RegEx options for Global search (more than one instance)
<add> // and for Multiline search
<add> var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
<add> theString = theString.replace(regEx, arguments[i]);
<add> }
<add>
<add> return theString;
<add> };
<add>
<add> /*var map = new Map("map", {
<add> basemap: "gray",
<add> center:[-79.792369,41.765298],
<add> zoom: 6
<add> });*/
<add>
<add> var _1mmap = new Map("courseMap", {
<add> basemap: "satellite",
<add> center:[-70.939625,42.860688],
<add> zoom: 16
<add> });
<add>
<add> var _halfmmap = new Map("halfcourseMap", {
<add> basemap: "satellite",
<add> center:[-70.939625,42.860688],
<add> zoom: 16
<add> });
<add>
<add> //Query to get the attributes
<add> var q = new Query();
<add> q.where = "1=1";
<add> q.outFields = ["*"];
<add>
<add> var qt = new QueryTask("https://services7.arcgis.com/Gk8wYdLBgQPxqVZU/arcgis/rest/services/LandSharkResults/FeatureServer/0");
<add>
<add> qt.on("complete",processData);
<add>
<add> qt.execute(q);
<add>
<add>
<add> var fLayer = new FeatureLayer("https://services7.arcgis.com/Gk8wYdLBgQPxqVZU/arcgis/rest/services/LandSharkResults/FeatureServer/0",{
<add> outFields:["*"],
<add> id:'swim'
<add> });
<add>
<add> //map.addLayer(fLayer);
<add> arcgisutils.createMap("a56c8aa0b35442d49b2ecb89ffb834e7","map");
<add>
<add> //atts = [];
<add> //on(dom.byId("btnC"), "click", function()
<add> var prpgrnRange = plt.d3.interpolateRgb('#40004b', '#00441b');
<add>
<add> var clrs;
<add> plt.d3.json("colorbrewer.json",function(clr){
<add> console.log(clr)
<add> clrs = clr;
<add> });
<add> processes = false;
<add>
<add> //fLayer.on("graphic-draw",function(grt)
<add> function processData(qRes)
<ide> {
<del> values:res,
<del> labels:labels,
<del> type:'pie'
<del> }
<del> ];
<del>
<del> var layout = {
<del> height: 400,
<del> width:500
<del> };
<del>
<del> plt.newPlot('_1MPieChart',data,layout,{displayModeBar:false});
<del>
<del>
<del>
<del>
<del>});
<add> /*
<add> if (atts.length < 133) {
<add>
<add> atts.push(grt.graphic.attributes)
<add> }
<add> if (atts.length == 133) {
<add> console.log(atts.length)*/
<add>
<add>
<add> var dt = moment('It is 2012-05-25', 'YYYY-MM-DD');
<add> console.log(dt)
<add>
<add>/*
<add> fLyr = map.getLayer('swim');
<add> console.log(fLyr);
<add>
<add> grps = fLyr.graphics*/
<add> /* grps.forEach(function (g) {
<add> atts.push(g.attributes)
<add> })*/
<add> atts = _.pluck(qRes.featureSet.features,"attributes")
<add>
<add>
<add> var eventgrpby = _.groupBy(atts, 'Event')
<add>
<add> //Charts for the Half mile
<add>
<add> var _halfmdivGrp = _.groupBy(eventgrpby["Half"], 'Div')
<add> console.log(_halfmdivGrp);
<add>
<add> //Get the top times and Competitors
<add> var halfTime = _.chain(eventgrpby.Half).flatten(true).pluck("Time").sortBy().value();
<add> var halfTopTime = halfTime[0]
<add>
<add>
<add> domConstruct.place(lang.replace("<tr><td>#Swimmers</td><td>{text}</td></tr><tr><td>Top Time</td><td>{tTime}</td></tr>", {
<add> text: halfTime.length.toString(),
<add> tTime: halfTopTime
<add> }), dom.byId("tBod"));
<add>
<add>
<add> var res = [];
<add> var labels = [];
<add> var boxPlotColor = {};
<add> _.each(_halfmdivGrp, function (elem, ind, list) {
<add> //var obj = {}
<add> //obj[ind] = elem.length;
<add> //res.push(obj)
<add> //var darray = [ind,elem.length]
<add>
<add>
<add> labels.push(ind)
<add> res.push(elem.length);
<add> var clrNum = (Math.random() * 4)
<add> boxPlotColor[ind] = prpgrnRange(clrNum);
<add> })
<add>
<add> //clrs["PRGn"][res.length]
<add> var data = [{
<add> values: res,
<add> labels: labels,
<add> type: "pie",
<add> marker: {
<add> colors: clrs["Paired"][res.length]
<add> }
<add> }];
<add>
<add> var layout = {
<add> height: 400,
<add> width: 500,
<add> paper_bgcolor: "darkgray",
<add> plot_bgcolor: "darkgray"
<add> };
<add>
<add> //Map the colors to a lookup
<add> lookup = _.object(labels, data[0].marker.colors)
<add>
<add>
<add> plt.newPlot("_HalfPieChart", data, layout, {displayModeBar: false});
<add>
<add>
<add> //Boxplots
<add>
<add> barHalfMDataChart = []
<add>
<add> _.each(_halfmdivGrp, function (e, i, l) {
<add> barHalfMData = {}
<add> var tData = []
<add> var ts = _.pluck(_halfmdivGrp[i], 'Time')
<add>
<add> d1 = moment(ts[0], "mm:ss:SS")
<add>
<add> _.each(ts, function (vals) {
<add>
<add> d2 = moment(vals, "mm:ss:SS")
<add> tmDiff = d2.diff(d1, "minutes")
<add> tData.push(tmDiff);
<add>
<add> })
<add>
<add> barHalfMData["x"] = tData;
<add> barHalfMData["type"] = "box";
<add> barHalfMData["name"] = i;
<add> barHalfMData["boxpoints"] = "all";
<add> barHalfMData["marker"] = {color: lookup[i]};//{"outliercolor": clrs["PRGn"][e.length][4].toString()};
<add> barHalfMDataChart.push(barHalfMData);
<add> });
<add>
<add>
<add> plt.newPlot("_HalfBoxPlot", barHalfMDataChart, {
<add> paper_bgcolor: "darkgray",
<add> plot_bgcolor: "darkgray"
<add> });//, layout);
<add>
<add> //end charts for the half
<add>
<add> //Charts for the 1 mile
<add>
<add> var _1mdivGrp = _.groupBy(eventgrpby["Mile"], 'Div')
<add> console.log(_1mdivGrp);
<add>
<add>
<add> //Get the top times and Competitors
<add> var mileTime = _.chain(eventgrpby.Mile).flatten(true).pluck("Time").sortBy().value();
<add> var mileTopTime = mileTime[0]
<add>
<add>
<add> domConstruct.place(lang.replace("<tr><td>#Swimmers</td><td>{text}</td></tr><tr><td>Top Time</td><td>{tTime}</td></tr>", {
<add> text: mileTime.length.toString(),
<add> tTime: mileTopTime
<add> }), dom.byId("tMileBod"));
<add>
<add>
<add> var res = [];
<add> var labels = [];
<add> _.each(_1mdivGrp, function (elem, ind, list) {
<add> //var obj = {}
<add> //obj[ind] = elem.length;
<add> //res.push(obj)
<add> //var darray = [ind,elem.length]
<add>
<add>
<add> labels.push(ind)
<add> res.push(elem.length);
<add> })
<add>
<add>
<add> var data = [{
<add> values: res,
<add> labels: labels,
<add> type: 'pie',
<add> marker: {
<add> colors: clrs["Paired"][res.length]
<add> }
<add> }];
<add>
<add> var layout = {
<add> height: 400,
<add> width: 500,
<add> paper_bgcolor: "darkgray",
<add> plot_bgcolor: "darkgray"
<add> };
<add>
<add> //Map the colors to a lookup
<add> lookup = _.object(labels, data[0].marker.colors)
<add> plt.newPlot('_1MPieChart', data, layout, {displayModeBar: false});
<add>
<add>
<add> //Boxplots
<add>
<add> bar1MDataChart = []
<add>
<add> _.each(_1mdivGrp, function (e, i, l) {
<add> bar1MData = {}
<add> var tData = []
<add> var ts = _.pluck(_1mdivGrp[i], 'Time')
<add>
<add> d1 = moment(ts[0], "mm:ss:SS")
<add>
<add> _.each(ts, function (vals) {
<add>
<add> d2 = moment(vals, "mm:ss:SS")
<add> tmDiff = d2.diff(d1, "minutes")
<add> tData.push(tmDiff)
<add>
<add> })
<add>
<add> bar1MData["x"] = tData;
<add> bar1MData["type"] = 'box';
<add> bar1MData["name"] = i;
<add> bar1MData["boxpoints"] = 'all';
<add> bar1MData["marker"] = {color: lookup[i]};
<add> bar1MDataChart.push(bar1MData);
<add> });
<add>
<add>
<add> plt.newPlot('_1MBoxPlot', bar1MDataChart, {
<add> paper_bgcolor: "darkgray",
<add> plot_bgcolor: "darkgray"
<add> })//, layout);
<add>
<add> //end 1 mile charts
<add>
<add> //Charts for the 2 mile
<add>
<add> var _2mdivGrp = _.groupBy(eventgrpby["2Mile"], 'Div')
<add>
<add>
<add> //Get the top times and Competitors
<add> var twomileTime = _.chain(eventgrpby["2Mile"]).flatten(true).pluck("Time").sortBy().value();
<add> var twomileModTime = []
<add> twomileTime.forEach(function (t) {
<add> if (t.charAt(0) == "1") {
<add> twomileModTime.push(moment(t.replace(t, t + ":00"), "h:mm:ss:SS"))
<add> }
<add> else if (t.charAt(0) != "1") {
<add> twomileModTime.push(moment("00:" + t, "h:mm:ss:SS"))
<add> }
<add> })
<add>
<add>
<add> var twomileTopTime = moment.min(twomileModTime)
<add>
<add>
<add> domConstruct.place(lang.replace("<tr><td>#Swimmers</td><td>{text}</td></tr><tr><td>Top Time</td><td>{tTime}</td></tr>", {
<add> text: twomileModTime.length.toString(),
<add> tTime: twomileTopTime._i
<add> }), dom.byId("tTwoMileBod"));
<add>
<add>
<add> var _2mres = [];
<add> var _2mlabels = [];
<add> _.each(_2mdivGrp, function (elem, ind, list) {
<add> //var obj = {}
<add> //obj[ind] = elem.length;
<add> //res.push(obj)
<add> //var darray = [ind,elem.length]
<add>
<add>
<add> _2mlabels.push(ind)
<add> _2mres.push(elem.length);
<add> })
<add>
<add>
<add> var _2data = [{
<add> values: _2mres,
<add> labels: _2mlabels,
<add> type: 'pie',
<add> marker: {
<add> colors: clrs["Paired"][res.length]
<add> }
<add> }];
<add>
<add> var _2layout = {
<add> height: 400,
<add> width: 500,
<add> paper_bgcolor: "darkgray",
<add> plot_bgcolor: "darkgray"
<add> };
<add> var lookup = _.object(labels, data[0].marker.colors)
<add> plt.newPlot('_2MPieChart', _2data, _2layout, {displayModeBar: false});
<add>
<add>
<add> //Boxplots
<add>
<add> bar2MDataChart = []
<add>
<add> _.each(_2mdivGrp, function (e, i, l) {
<add> bar2MData = {}
<add> var _2tData = []
<add> var _2mts = _.pluck(_2mdivGrp[i], 'Time')
<add>
<add> _2md1 = moment(_2mts[0], "mm:ss:SS")
<add>
<add> _.each(_2mts, function (_2mvals) {
<add>
<add> if (_2mvals.charAt(0) == 1) {
<add> _2md2 = moment(_2mvals, "h:mm:ss")
<add> }
<add> else {
<add> var n_2mvals = "0:" + _2mvals
<add> _2md2 = moment(n_2mvals, "h:mm:ss:SS")
<add> }
<add>
<add>
<add> _2mtmDiff = _2md2.diff(_2md1, "minutes")
<add> _2tData.push(_2mtmDiff)
<add>
<add> })
<add>
<add> bar2MData["x"] = _2tData;
<add> bar2MData["type"] = 'box';
<add> bar2MData["name"] = i;
<add> bar2MData["boxpoints"] = 'all';
<add> bar2MData["marker"] = {color: lookup[i]};
<add> bar2MDataChart.push(bar2MData);
<add> });
<add>
<add>
<add> plt.newPlot('_2MBoxPlot', bar2MDataChart, {paper_bgcolor: "darkgray", plot_bgcolor: "darkgray"})//, layout);
<add>
<add> //end 2 mile charts
<add>
<add>
<add> //end of else
<add>
<add> };
<add>
<add>
<add>
<add>
<add> /* fLayer.on("load",function(l){
<add> console.log(l.layer.graphics);
<add>
<add>
<add>
<add> })*/
<add>
<add> //atts2 = []
<add> /*fLayer.on("graphic-draw",function(grt){
<add>
<add> if(atts2.length < 133) {
<add>
<add> atts2.push(grt.graphic.attributes)
<add> if (atts2.length ==133){
<add> console.log(atts2.length)
<add> }
<add>
<add> }})*/
<add>
<add> });
<add>
<add>
<add>
<add>
<add>
<add> |
|
Java | lgpl-2.1 | f5e28c5668114799e2d4e90a8e52b6948cec47b8 | 0 | ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror | /*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
GNU Lesser General Public License
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package jade.domain;
/**
* This class provides a single access point for the
* set of constants
* already defined by FIPA.
* The constants have been grouped by category (i.e. ACLCodecs,
* Content Languages, MTPs, ...), with one inner class implementing each
* category.
* @author Fabio Bellifemine - TILab
* @version $Date$ $Revision$
**/
public interface FIPANames {
/**
* Set of constants that identifies the Codec of ACL Messages and
* that can be assigned via
* <code> ACLMessage.getEnvelope().setAclRepresentation(FIPANames.ACLCodec.BITEFFICIENT); </code>
**/
public static interface ACLCodec {
/** Syntactic representation of ACL in string form
* @see <a href=http://www.fipa.org/specs/fipa00070/XC00070f.html>FIPA Spec</a>
**/
public static final String STRING = "fipa.acl.rep.string.std";
/** Syntactic representation of ACL in XML form
* @see <a href=http://www.fipa.org/specs/fipa00071/XC00071b.html>FIPA Spec</a>
**/
public static final String XML = "fipa.acl.rep.xml.std";
/** Syntactic representation of ACL in XML form
* @see <a href=http://www.fipa.org/specs/fipa00069/XC00069e.html>FIPA Spec</a>
**/
public static final String BITEFFICIENT = "fipa.acl.rep.bitefficient.std";
}
/**
* Set of constants that identifies the Interaction Protocols and that
* can be assigned via
* <code>ACLMessage.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST)
* </code>
**/
public static interface InteractionProtocol {
//achieve rational effect protocol
public static final String FIPA_REQUEST = "fipa-request";
public static final String FIPA_QUERY = "fipa-query" ;
public static final String FIPA_REQUEST_WHEN = "fipa-request-when";
public static final String FIPA_BROKERING = "fipa-brokering";
public static final String FIPA_RECRUITING = "fipa-recruiting";
public static final String FIPA_PROPOSE = "fipa-propose";
//auction protocol
public static final String FIPA_ENGLISH_AUCTION = "fipa-auction-english";
public static final String FIPA_DUTCH_AUCTION = "fipa-auction-dutch";
public static final String FIPA_CONTRACT_NET = "fipa-contract-net";
public static final String FIPA_ITERATED_CONTRACT_NET = "fipa-iterated-contract-net";
}
/**
* Set of constants that identifies the content languages and that
* can be assigned via
* <code>ACLMessage.setLanguage(FIPANames.ContentLanguage.SL0)
* </code>
**/
public static interface ContentLanguage {
public static final String FIPA_SL0 = "fipa-sl0";
public static final String FIPA_SL1 = "fipa-sl1";
public static final String FIPA_SL2 = "fipa-sl2";
public static final String FIPA_SL = "fipa-sl";
}
/**
* Set of constants that identifies the Message Transport Protocols.
**/
public static interface MTP {
/**
* IIOP-based MTP
* @see <a href=http://www.fipa.org/specs/fipa00075/XC00075e.html>FIPA Spec</a>
**/
public static final String IIOP = "fipa.mts.mtp.iiop.std";
/**
* WAP-based MTP
* @see <a href=http://www.fipa.org/specs/fipa00076/XC00076c.html>FIPA Spec</a>
**/
public static final String WAP = "fipa.mts.mtp.wap.std";
/**
* HTTP-based MTP
* @see <a href=http://www.fipa.org/specs/fipa00084/XC00084d.html>FIPA Spec</a>
**/
public static final String HTTP = "fipa.mts.mtp.http.std";
}
}
| src/jade/domain/FIPANames.java | /*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
GNU Lesser General Public License
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package jade.domain;
/**
* This class provides a single access point for the
* set of constants
* already defined by FIPA.
* The constants have been grouped by category (i.e. ACLCodecs,
* Content Languages, MTPs, ...), with one inner class implementing each
* category.
* @author Fabio Bellifemine - TILab
* @version $Date$ $Revision$
**/
public class FIPANames {
/**
* Set of constants that identifies the Codec of ACL Messages and
* that can be assigned via
* <code> ACLMessage.getEnvelope().setAclRepresentation(FIPANames.ACLCodec.BITEFFICIENT); </code>
**/
public static class ACLCodec {
/** Syntactic representation of ACL in string form
* @see <a href=http://www.fipa.org/specs/fipa00070/XC00070f.html>FIPA Spec</a>
**/
public static final String STRING = "fipa.acl.rep.string.std";
/** Syntactic representation of ACL in XML form
* @see <a href=http://www.fipa.org/specs/fipa00071/XC00071b.html>FIPA Spec</a>
**/
public static final String XML = "fipa.acl.rep.xml.std";
/** Syntactic representation of ACL in XML form
* @see <a href=http://www.fipa.org/specs/fipa00069/XC00069e.html>FIPA Spec</a>
**/
public static final String BITEFFICIENT = "fipa.acl.rep.bitefficient.std";
}
/**
* Set of constants that identifies the Interaction Protocols and that
* can be assigned via
* <code>ACLMessage.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST)
* </code>
**/
public static class InteractionProtocol implements jade.proto.FIPAProtocolNames {
}
/**
* Set of constants that identifies the content languages and that
* can be assigned via
* <code>ACLMessage.setLanguage(FIPANames.ContentLanguage.SL0)
* </code>
**/
public static class ContentLanguage {
public static final String FIPA_SL0 = "FIPA-SL0";
public static final String FIPA_SL1 = "FIPA-SL1";
public static final String FIPA_SL2 = "FIPA-SL2";
public static final String FIPA_SL = "FIPA-SL";
}
/**
* Set of constants that identifies the Message Transport Protocols.
**/
public static class MTP {
/**
* IIOP-based MTP
* @see <a href=http://www.fipa.org/specs/fipa00075/XC00075e.html>FIPA Spec</a>
**/
public static final String IIOP = "fipa.mts.mtp.iiop.std";
/**
* WAP-based MTP
* @see <a href=http://www.fipa.org/specs/fipa00076/XC00076c.html>FIPA Spec</a>
**/
public static final String WAP = "fipa.mts.mtp.wap.std";
/**
* HTTP-based MTP
* @see <a href=http://www.fipa.org/specs/fipa00084/XC00084d.html>FIPA Spec</a>
**/
public static final String HTTP = "fipa.mts.mtp.http.std";
}
}
| Transformed into an interface
| src/jade/domain/FIPANames.java | Transformed into an interface | <ide><path>rc/jade/domain/FIPANames.java
<ide> * @version $Date$ $Revision$
<ide> **/
<ide>
<del>public class FIPANames {
<add>public interface FIPANames {
<ide> /**
<ide> * Set of constants that identifies the Codec of ACL Messages and
<ide> * that can be assigned via
<ide> * <code> ACLMessage.getEnvelope().setAclRepresentation(FIPANames.ACLCodec.BITEFFICIENT); </code>
<ide> **/
<del> public static class ACLCodec {
<add> public static interface ACLCodec {
<ide> /** Syntactic representation of ACL in string form
<ide> * @see <a href=http://www.fipa.org/specs/fipa00070/XC00070f.html>FIPA Spec</a>
<ide> **/
<ide> * <code>ACLMessage.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST)
<ide> * </code>
<ide> **/
<del> public static class InteractionProtocol implements jade.proto.FIPAProtocolNames {
<add> public static interface InteractionProtocol {
<add> //achieve rational effect protocol
<add> public static final String FIPA_REQUEST = "fipa-request";
<add> public static final String FIPA_QUERY = "fipa-query" ;
<add> public static final String FIPA_REQUEST_WHEN = "fipa-request-when";
<add> public static final String FIPA_BROKERING = "fipa-brokering";
<add> public static final String FIPA_RECRUITING = "fipa-recruiting";
<add> public static final String FIPA_PROPOSE = "fipa-propose";
<add>
<add> //auction protocol
<add> public static final String FIPA_ENGLISH_AUCTION = "fipa-auction-english";
<add> public static final String FIPA_DUTCH_AUCTION = "fipa-auction-dutch";
<add>
<add>
<add> public static final String FIPA_CONTRACT_NET = "fipa-contract-net";
<add> public static final String FIPA_ITERATED_CONTRACT_NET = "fipa-iterated-contract-net";
<ide> }
<ide>
<ide> /**
<ide> * <code>ACLMessage.setLanguage(FIPANames.ContentLanguage.SL0)
<ide> * </code>
<ide> **/
<del> public static class ContentLanguage {
<del> public static final String FIPA_SL0 = "FIPA-SL0";
<del> public static final String FIPA_SL1 = "FIPA-SL1";
<del> public static final String FIPA_SL2 = "FIPA-SL2";
<del> public static final String FIPA_SL = "FIPA-SL";
<add> public static interface ContentLanguage {
<add> public static final String FIPA_SL0 = "fipa-sl0";
<add> public static final String FIPA_SL1 = "fipa-sl1";
<add> public static final String FIPA_SL2 = "fipa-sl2";
<add> public static final String FIPA_SL = "fipa-sl";
<ide> }
<ide>
<ide> /**
<ide> * Set of constants that identifies the Message Transport Protocols.
<ide> **/
<del> public static class MTP {
<add> public static interface MTP {
<ide> /**
<ide> * IIOP-based MTP
<ide> * @see <a href=http://www.fipa.org/specs/fipa00075/XC00075e.html>FIPA Spec</a> |
|
Java | apache-2.0 | 47d32c904afd20c939384f7747878a587cd62aaf | 0 | mglukhikh/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,kool79/intellij-community,apixandru/intellij-community,xfournet/intellij-community,amith01994/intellij-community,fitermay/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,supersven/intellij-community,amith01994/intellij-community,hurricup/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,da1z/intellij-community,FHannes/intellij-community,ibinti/intellij-community,izonder/intellij-community,samthor/intellij-community,slisson/intellij-community,caot/intellij-community,slisson/intellij-community,da1z/intellij-community,apixandru/intellij-community,fitermay/intellij-community,petteyg/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,signed/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,slisson/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,samthor/intellij-community,ibinti/intellij-community,joewalnes/idea-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,signed/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,slisson/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,da1z/intellij-community,jexp/idea2,adedayo/intellij-community,joewalnes/idea-community,signed/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,signed/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,semonte/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,joewalnes/idea-community,robovm/robovm-studio,fnouama/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,vladmm/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,xfournet/intellij-community,ernestp/consulo,SerCeMan/intellij-community,apixandru/intellij-community,fnouama/intellij-community,kool79/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,vladmm/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,samthor/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,consulo/consulo,da1z/intellij-community,supersven/intellij-community,supersven/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,jexp/idea2,xfournet/intellij-community,caot/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,signed/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,izonder/intellij-community,xfournet/intellij-community,ibinti/intellij-community,jagguli/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,apixandru/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,ernestp/consulo,gnuhub/intellij-community,izonder/intellij-community,orekyuu/intellij-community,samthor/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,hurricup/intellij-community,signed/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,vladmm/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,allotria/intellij-community,jexp/idea2,lucafavatella/intellij-community,robovm/robovm-studio,hurricup/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,amith01994/intellij-community,vladmm/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,caot/intellij-community,da1z/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,kool79/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,semonte/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,robovm/robovm-studio,retomerz/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,retomerz/intellij-community,apixandru/intellij-community,allotria/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,retomerz/intellij-community,asedunov/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,da1z/intellij-community,samthor/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,ryano144/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,da1z/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,da1z/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,samthor/intellij-community,slisson/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,hurricup/intellij-community,xfournet/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,ryano144/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,blademainer/intellij-community,signed/intellij-community,retomerz/intellij-community,blademainer/intellij-community,amith01994/intellij-community,robovm/robovm-studio,fitermay/intellij-community,izonder/intellij-community,allotria/intellij-community,consulo/consulo,caot/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,ernestp/consulo,ftomassetti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,samthor/intellij-community,jexp/idea2,clumsy/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,caot/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,allotria/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,jagguli/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,ibinti/intellij-community,semonte/intellij-community,signed/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,hurricup/intellij-community,holmes/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,tmpgit/intellij-community,consulo/consulo,diorcety/intellij-community,kdwink/intellij-community,holmes/intellij-community,hurricup/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,diorcety/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,kool79/intellij-community,diorcety/intellij-community,apixandru/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,ernestp/consulo,ftomassetti/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,semonte/intellij-community,semonte/intellij-community,hurricup/intellij-community,supersven/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,jexp/idea2,petteyg/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,retomerz/intellij-community,amith01994/intellij-community,asedunov/intellij-community,FHannes/intellij-community,kool79/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,kdwink/intellij-community,caot/intellij-community,signed/intellij-community,jexp/idea2,vvv1559/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,clumsy/intellij-community,blademainer/intellij-community,vladmm/intellij-community,amith01994/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,ernestp/consulo,da1z/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,retomerz/intellij-community,kool79/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,kool79/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,signed/intellij-community,consulo/consulo,da1z/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,semonte/intellij-community,adedayo/intellij-community,signed/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,allotria/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,vladmm/intellij-community,holmes/intellij-community,slisson/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,da1z/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,caot/intellij-community,ryano144/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,dslomov/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,allotria/intellij-community,clumsy/intellij-community,holmes/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,samthor/intellij-community,kool79/intellij-community,caot/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,amith01994/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,caot/intellij-community,fnouama/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,allotria/intellij-community,dslomov/intellij-community,blademainer/intellij-community,retomerz/intellij-community,kdwink/intellij-community,FHannes/intellij-community,supersven/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,FHannes/intellij-community,jexp/idea2,supersven/intellij-community,adedayo/intellij-community,retomerz/intellij-community,dslomov/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,jagguli/intellij-community,ibinti/intellij-community,dslomov/intellij-community,ryano144/intellij-community,fitermay/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,robovm/robovm-studio,supersven/intellij-community,semonte/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,joewalnes/idea-community,joewalnes/idea-community,hurricup/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,caot/intellij-community,amith01994/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,blademainer/intellij-community,FHannes/intellij-community,kool79/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,salguarnieri/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,dslomov/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,consulo/consulo,jexp/idea2,suncycheng/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,kool79/intellij-community | package com.intellij.history.integration.ui.actions;
import com.intellij.history.core.ILocalVcs;
import com.intellij.history.integration.IdeaGateway;
import com.intellij.history.integration.LocalHistoryComponent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
public abstract class LocalHistoryAction extends AnAction {
@Override
public void update(AnActionEvent e) {
Presentation p = e.getPresentation();
if (getProject(e) == null) {
p.setVisible(false);
p.setEnabled(false);
return;
}
p.setVisible(true);
p.setText(getText(e), true);
p.setEnabled(isEnabled(getVcs(e), getGateway(e), getFile(e), e));
}
protected String getText(AnActionEvent e) {
return e.getPresentation().getTextWithMnemonic();
}
protected boolean isEnabled(ILocalVcs vcs, IdeaGateway gw, VirtualFile f, AnActionEvent e) {
return true;
}
protected ILocalVcs getVcs(AnActionEvent e) {
return LocalHistoryComponent.getLocalVcsFor(getProject(e));
}
protected IdeaGateway getGateway(AnActionEvent e) {
return new IdeaGateway(getProject(e));
}
protected VirtualFile getFile(AnActionEvent e) {
VirtualFile[] ff = getFiles(e);
return (ff == null || ff.length != 1) ? null : ff[0];
}
private VirtualFile[] getFiles(AnActionEvent e) {
return e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);
}
private Project getProject(AnActionEvent e) {
return e.getData(PlatformDataKeys.PROJECT);
}
}
| lvcs/impl/src/com/intellij/history/integration/ui/actions/LocalHistoryAction.java | package com.intellij.history.integration.ui.actions;
import com.intellij.history.core.ILocalVcs;
import com.intellij.history.integration.IdeaGateway;
import com.intellij.history.integration.LocalHistoryComponent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
public abstract class LocalHistoryAction extends AnAction {
@Override
public void update(AnActionEvent e) {
Presentation p = e.getPresentation();
if (getProject(e) == null) {
p.setVisible(false);
p.setEnabled(false);
return;
}
p.setText(getText(e), true);
p.setEnabled(isEnabled(getVcs(e), getGateway(e), getFile(e), e));
}
protected String getText(AnActionEvent e) {
return e.getPresentation().getTextWithMnemonic();
}
protected boolean isEnabled(ILocalVcs vcs, IdeaGateway gw, VirtualFile f, AnActionEvent e) {
return true;
}
protected ILocalVcs getVcs(AnActionEvent e) {
return LocalHistoryComponent.getLocalVcsFor(getProject(e));
}
protected IdeaGateway getGateway(AnActionEvent e) {
return new IdeaGateway(getProject(e));
}
protected VirtualFile getFile(AnActionEvent e) {
VirtualFile[] ff = getFiles(e);
return (ff == null || ff.length != 1) ? null : ff[0];
}
private VirtualFile[] getFiles(AnActionEvent e) {
return e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);
}
private Project getProject(AnActionEvent e) {
return e.getData(PlatformDataKeys.PROJECT);
}
}
| visibility update fix
| lvcs/impl/src/com/intellij/history/integration/ui/actions/LocalHistoryAction.java | visibility update fix | <ide><path>vcs/impl/src/com/intellij/history/integration/ui/actions/LocalHistoryAction.java
<ide> p.setEnabled(false);
<ide> return;
<ide> }
<add> p.setVisible(true);
<ide> p.setText(getText(e), true);
<ide> p.setEnabled(isEnabled(getVcs(e), getGateway(e), getFile(e), e));
<ide> } |
|
Java | apache-2.0 | b38e48a3f1fa890adc1e2aaaf5b26f6153e202cf | 0 | Hipparchus-Math/hipparchus,apache/commons-math,apache/commons-math,apache/commons-math,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus,sdinot/hipparchus,apache/commons-math,sdinot/hipparchus,sdinot/hipparchus,Hipparchus-Math/hipparchus,sdinot/hipparchus | /*
* Copyright 2004 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.commons.math.fraction;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import junit.framework.TestCase;
public class FractionFormatTest extends TestCase {
FractionFormat properFormat = null;
FractionFormat improperFormat = null;
protected Locale getLocale() {
return Locale.getDefault();
}
protected void setUp() throws Exception {
properFormat = FractionFormat.getProperInstance(getLocale());
improperFormat = FractionFormat.getImproperInstance(getLocale());
}
public void testFormat() {
Fraction c = new Fraction(1, 2);
String expected = "1 / 2";
String actual = properFormat.format(c);
assertEquals(expected, actual);
actual = improperFormat.format(c);
assertEquals(expected, actual);
}
public void testFormatNegative() {
Fraction c = new Fraction(-1, 2);
String expected = "-1 / 2";
String actual = properFormat.format(c);
assertEquals(expected, actual);
actual = improperFormat.format(c);
assertEquals(expected, actual);
}
public void testFormatZero() {
Fraction c = new Fraction(0, 1);
String expected = "0 / 1";
String actual = properFormat.format(c);
assertEquals(expected, actual);
actual = improperFormat.format(c);
assertEquals(expected, actual);
}
public void testFormatImproper() {
Fraction c = new Fraction(5, 3);
String actual = properFormat.format(c);
assertEquals("1 2 / 3", actual);
actual = improperFormat.format(c);
assertEquals("5 / 3", actual);
}
public void testFormatImproperNegative() {
Fraction c = new Fraction(-5, 3);
String actual = properFormat.format(c);
assertEquals("-1 2 / 3", actual);
actual = improperFormat.format(c);
assertEquals("-5 / 3", actual);
}
public void testParse() {
String source = "1 / 2";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(1, c.getNumerator());
assertEquals(2, c.getDenominator());
c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(1, c.getNumerator());
assertEquals(2, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
}
public void testParseInteger() {
String source = "10";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(10, c.getNumerator());
assertEquals(1, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
try {
Fraction c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(10, c.getNumerator());
assertEquals(1, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
}
public void testParseInvalid() {
String source = "a";
String msg = "should not be able to parse '10 / a'.";
try {
properFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
try {
improperFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
}
public void testParseInvalidDenominator() {
String source = "10 / a";
String msg = "should not be able to parse '10 / a'.";
try {
properFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
try {
improperFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
}
public void testParseNegative() {
try {
String source = "-1 / 2";
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
source = "1 / -2";
c = properFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
}
public void testParseProper() {
String source = "1 2 / 3";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(5, c.getNumerator());
assertEquals(3, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
try {
improperFormat.parse(source);
fail("invalid improper fraction.");
} catch (ParseException ex) {
// success
}
}
public void testParseProperNegative() {
String source = "-1 2 / 3";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(-5, c.getNumerator());
assertEquals(3, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
try {
improperFormat.parse(source);
fail("invalid improper fraction.");
} catch (ParseException ex) {
// success
}
}
public void testNumeratorFormat() {
NumberFormat old = properFormat.getNumeratorFormat();
NumberFormat nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
properFormat.setNumeratorFormat(nf);
assertEquals(nf, properFormat.getNumeratorFormat());
properFormat.setNumeratorFormat(old);
old = improperFormat.getNumeratorFormat();
nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
improperFormat.setNumeratorFormat(nf);
assertEquals(nf, improperFormat.getNumeratorFormat());
improperFormat.setNumeratorFormat(old);
}
public void testDenominatorFormat() {
NumberFormat old = properFormat.getDenominatorFormat();
NumberFormat nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
properFormat.setDenominatorFormat(nf);
assertEquals(nf, properFormat.getDenominatorFormat());
properFormat.setDenominatorFormat(old);
old = improperFormat.getDenominatorFormat();
nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
improperFormat.setDenominatorFormat(nf);
assertEquals(nf, improperFormat.getDenominatorFormat());
improperFormat.setDenominatorFormat(old);
}
public void testWholeFormat() {
ProperFractionFormat format = (ProperFractionFormat)properFormat;
NumberFormat old = format.getWholeFormat();
NumberFormat nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
format.setWholeFormat(nf);
assertEquals(nf, format.getWholeFormat());
format.setWholeFormat(old);
}
}
| src/test/org/apache/commons/math/fraction/FractionFormatTest.java | /*
* Copyright 2004 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.commons.math.fraction;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import junit.framework.TestCase;
public class FractionFormatTest extends TestCase {
FractionFormat properFormat = null;
FractionFormat improperFormat = null;
protected Locale getLocale() {
return Locale.getDefault();
}
protected void setUp() throws Exception {
properFormat = FractionFormat.getProperInstance(getLocale());
improperFormat = FractionFormat.getImproperInstance(getLocale());
}
public void testFormat() {
Fraction c = new Fraction(1, 2);
String expected = "1 / 2";
String actual = properFormat.format(c);
assertEquals(expected, actual);
actual = improperFormat.format(c);
assertEquals(expected, actual);
}
public void testFormatNegative() {
Fraction c = new Fraction(-1, 2);
String expected = "-1 / 2";
String actual = properFormat.format(c);
assertEquals(expected, actual);
actual = improperFormat.format(c);
assertEquals(expected, actual);
}
public void testFormatZero() {
Fraction c = new Fraction(0, 1);
String expected = "0 / 1";
String actual = properFormat.format(c);
assertEquals(expected, actual);
actual = improperFormat.format(c);
assertEquals(expected, actual);
}
public void testFormatImproper() {
Fraction c = new Fraction(5, 3);
String actual = properFormat.format(c);
assertEquals("1 2 / 3", actual);
actual = improperFormat.format(c);
assertEquals("5 / 3", actual);
}
public void testFormatImproperNegative() {
Fraction c = new Fraction(-5, 3);
String actual = properFormat.format(c);
assertEquals("-1 2 / 3", actual);
actual = improperFormat.format(c);
assertEquals("-5 / 3", actual);
}
public void testParse() {
String source = "1 / 2";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(1, c.getNumerator());
assertEquals(2, c.getDenominator());
c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(1, c.getNumerator());
assertEquals(2, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
}
public void testParseInteger() {
String source = "10";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(10, c.getNumerator());
assertEquals(1, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
try {
Fraction c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(10, c.getNumerator());
assertEquals(1, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
}
public void testParseInvalid() {
String source = "a";
String msg = "should not be able to parse '10 / a'.";
try {
properFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
try {
improperFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
}
public void testParseInvalidDenominator() {
String source = "10 / a";
String msg = "should not be able to parse '10 / a'.";
try {
properFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
try {
improperFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
}
public void testParseNegative() {
try {
String source = "-1 / 2";
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
source = "1 / -2";
c = properFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
}
public void testParseProper() {
String source = "1 2 / 3";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(5, c.getNumerator());
assertEquals(3, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
try {
improperFormat.parse(source);
fail("invalid improper fraction.");
} catch (ParseException ex) {
// success
}
}
public void testParseProperNegative() {
String source = "-1 2 / 3";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(-5, c.getNumerator());
assertEquals(3, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
try {
improperFormat.parse(source);
fail("invalid improper fraction.");
} catch (ParseException ex) {
// success
}
}
public void testNumeratorFormat() {
NumberFormat old = properFormat.getNumeratorFormat();
NumberFormat nf = NumberFormat.getIntegerInstance();
properFormat.setNumeratorFormat(nf);
assertEquals(nf, properFormat.getNumeratorFormat());
properFormat.setNumeratorFormat(old);
old = improperFormat.getNumeratorFormat();
nf = NumberFormat.getIntegerInstance();
improperFormat.setNumeratorFormat(nf);
assertEquals(nf, improperFormat.getNumeratorFormat());
improperFormat.setNumeratorFormat(old);
}
public void testDenominatorFormat() {
NumberFormat old = properFormat.getDenominatorFormat();
NumberFormat nf = NumberFormat.getIntegerInstance();
properFormat.setDenominatorFormat(nf);
assertEquals(nf, properFormat.getDenominatorFormat());
properFormat.setDenominatorFormat(old);
old = improperFormat.getDenominatorFormat();
nf = NumberFormat.getIntegerInstance();
improperFormat.setDenominatorFormat(nf);
assertEquals(nf, improperFormat.getDenominatorFormat());
improperFormat.setDenominatorFormat(old);
}
public void testWholeFormat() {
ProperFractionFormat format = (ProperFractionFormat)properFormat;
NumberFormat old = format.getWholeFormat();
NumberFormat nf = NumberFormat.getIntegerInstance();
format.setWholeFormat(nf);
assertEquals(nf, format.getWholeFormat());
format.setWholeFormat(old);
}
}
| Removed jdk 1.4 dependency in FractionFormatTest.
git-svn-id: ba027325f5cbd8d0def94cfab53a7170165593ea@388870 13f79535-47bb-0310-9956-ffa450edef68
| src/test/org/apache/commons/math/fraction/FractionFormatTest.java | Removed jdk 1.4 dependency in FractionFormatTest. | <ide><path>rc/test/org/apache/commons/math/fraction/FractionFormatTest.java
<ide>
<ide> public void testNumeratorFormat() {
<ide> NumberFormat old = properFormat.getNumeratorFormat();
<del> NumberFormat nf = NumberFormat.getIntegerInstance();
<add> NumberFormat nf = NumberFormat.getInstance();
<add> nf.setParseIntegerOnly(true);
<ide> properFormat.setNumeratorFormat(nf);
<ide> assertEquals(nf, properFormat.getNumeratorFormat());
<ide> properFormat.setNumeratorFormat(old);
<ide>
<ide> old = improperFormat.getNumeratorFormat();
<del> nf = NumberFormat.getIntegerInstance();
<add> nf = NumberFormat.getInstance();
<add> nf.setParseIntegerOnly(true);
<ide> improperFormat.setNumeratorFormat(nf);
<ide> assertEquals(nf, improperFormat.getNumeratorFormat());
<ide> improperFormat.setNumeratorFormat(old);
<ide>
<ide> public void testDenominatorFormat() {
<ide> NumberFormat old = properFormat.getDenominatorFormat();
<del> NumberFormat nf = NumberFormat.getIntegerInstance();
<add> NumberFormat nf = NumberFormat.getInstance();
<add> nf.setParseIntegerOnly(true);
<ide> properFormat.setDenominatorFormat(nf);
<ide> assertEquals(nf, properFormat.getDenominatorFormat());
<ide> properFormat.setDenominatorFormat(old);
<ide>
<ide> old = improperFormat.getDenominatorFormat();
<del> nf = NumberFormat.getIntegerInstance();
<add> nf = NumberFormat.getInstance();
<add> nf.setParseIntegerOnly(true);
<ide> improperFormat.setDenominatorFormat(nf);
<ide> assertEquals(nf, improperFormat.getDenominatorFormat());
<ide> improperFormat.setDenominatorFormat(old);
<ide> ProperFractionFormat format = (ProperFractionFormat)properFormat;
<ide>
<ide> NumberFormat old = format.getWholeFormat();
<del> NumberFormat nf = NumberFormat.getIntegerInstance();
<add> NumberFormat nf = NumberFormat.getInstance();
<add> nf.setParseIntegerOnly(true);
<ide> format.setWholeFormat(nf);
<ide> assertEquals(nf, format.getWholeFormat());
<ide> format.setWholeFormat(old); |
|
Java | apache-2.0 | c6e9b6717e29b4d8dcdcca4362f1748a2a550e6e | 0 | APriestman/autopsy,rcordovano/autopsy,wschaeferB/autopsy,dgrove727/autopsy,APriestman/autopsy,APriestman/autopsy,narfindustries/autopsy,esaunders/autopsy,wschaeferB/autopsy,narfindustries/autopsy,millmanorama/autopsy,APriestman/autopsy,APriestman/autopsy,wschaeferB/autopsy,esaunders/autopsy,wschaeferB/autopsy,rcordovano/autopsy,wschaeferB/autopsy,narfindustries/autopsy,dgrove727/autopsy,rcordovano/autopsy,esaunders/autopsy,rcordovano/autopsy,millmanorama/autopsy,millmanorama/autopsy,APriestman/autopsy,esaunders/autopsy,rcordovano/autopsy,rcordovano/autopsy,esaunders/autopsy,APriestman/autopsy,dgrove727/autopsy,millmanorama/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2011-2016 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.timeline.ui.listvew;
import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.stream.Collectors;
import javafx.application.Platform;
import javafx.beans.Observable;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.OverrunStyle;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.util.Callback;
import javax.swing.Action;
import javax.swing.JMenuItem;
import org.controlsfx.control.Notifications;
import org.openide.awt.Actions;
import org.openide.util.NbBundle;
import org.openide.util.actions.Presenter;
import org.sleuthkit.autopsy.casemodule.services.TagsManager;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.ThreadConfined;
import org.sleuthkit.autopsy.timeline.FXMLConstructor;
import org.sleuthkit.autopsy.timeline.TimeLineController;
import org.sleuthkit.autopsy.timeline.datamodel.CombinedEvent;
import org.sleuthkit.autopsy.timeline.datamodel.SingleEvent;
import org.sleuthkit.autopsy.timeline.datamodel.eventtype.BaseTypes;
import org.sleuthkit.autopsy.timeline.datamodel.eventtype.FileSystemTypes;
import org.sleuthkit.autopsy.timeline.explorernodes.EventNode;
import org.sleuthkit.autopsy.timeline.zooming.DescriptionLoD;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskCoreException;
/**
* The inner component that makes up the List view. Manages the TableView.
*/
class ListTimeline extends BorderPane {
private static final Logger LOGGER = Logger.getLogger(ListTimeline.class.getName());
/**
* call-back used to wrap the CombinedEvent in a ObservableValue
*/
private static final Callback<TableColumn.CellDataFeatures<CombinedEvent, CombinedEvent>, ObservableValue<CombinedEvent>> CELL_VALUE_FACTORY = param -> new SimpleObjectProperty<>(param.getValue());
@FXML
private Label eventCountLabel;
@FXML
private TableView<CombinedEvent> table;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> idColumn;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> dateTimeColumn;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> descriptionColumn;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> typeColumn;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> knownColumn;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> taggedColumn;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> hashHitColumn;
private final TimeLineController controller;
/**
* Observable list used to track selected events.
*/
private final ObservableList<Long> selectedEventIDs = FXCollections.observableArrayList();
private final SleuthkitCase sleuthkitCase;
private final TagsManager tagsManager;
/**
* Constructor
*
* @param controller The controller for this timeline
*/
ListTimeline(TimeLineController controller) {
this.controller = controller;
sleuthkitCase = controller.getAutopsyCase().getSleuthkitCase();
tagsManager = controller.getAutopsyCase().getServices().getTagsManager();
FXMLConstructor.construct(this, ListTimeline.class, "ListTimeline.fxml");
}
@FXML
@NbBundle.Messages({
"# {0} - the number of events",
"ListTimeline.eventCountLabel.text={0} events"})
void initialize() {
assert eventCountLabel != null : "fx:id=\"eventCountLabel\" was not injected: check your FXML file 'ListViewPane.fxml'.";
assert table != null : "fx:id=\"table\" was not injected: check your FXML file 'ListViewPane.fxml'.";
assert idColumn != null : "fx:id=\"idColumn\" was not injected: check your FXML file 'ListViewPane.fxml'.";
assert dateTimeColumn != null : "fx:id=\"dateTimeColumn\" was not injected: check your FXML file 'ListViewPane.fxml'.";
assert descriptionColumn != null : "fx:id=\"descriptionColumn\" was not injected: check your FXML file 'ListViewPane.fxml'.";
assert typeColumn != null : "fx:id=\"typeColumn\" was not injected: check your FXML file 'ListViewPane.fxml'.";
assert knownColumn != null : "fx:id=\"knownColumn\" was not injected: check your FXML file 'ListViewPane.fxml'.";
//override default row with one that provides context menus
table.setRowFactory(tableView -> new EventRow());
//remove idColumn (can be restored for debugging).
table.getColumns().remove(idColumn);
//// set up cell and cell-value factories for columns
dateTimeColumn.setCellValueFactory(CELL_VALUE_FACTORY);
dateTimeColumn.setCellFactory(col -> new TextEventTableCell(singleEvent ->
TimeLineController.getZonedFormatter().print(singleEvent.getStartMillis())));
descriptionColumn.setCellValueFactory(CELL_VALUE_FACTORY);
descriptionColumn.setCellFactory(col -> new TextEventTableCell(singleEvent ->
singleEvent.getDescription(DescriptionLoD.FULL)));
typeColumn.setCellValueFactory(CELL_VALUE_FACTORY);
typeColumn.setCellFactory(col -> new EventTypeCell());
knownColumn.setCellValueFactory(CELL_VALUE_FACTORY);
knownColumn.setCellFactory(col -> new TextEventTableCell(singleEvent ->
singleEvent.getKnown().getName()));
taggedColumn.setCellValueFactory(CELL_VALUE_FACTORY);
taggedColumn.setCellFactory(col -> new TaggedCell());
hashHitColumn.setCellValueFactory(CELL_VALUE_FACTORY);
hashHitColumn.setCellFactory(col -> new HashHitCell());
//bind event count label to number of items in the table
eventCountLabel.textProperty().bind(new StringBinding() {
{
bind(table.getItems());
}
@Override
protected String computeValue() {
return Bundle.ListTimeline_eventCountLabel_text(table.getItems().size());
}
});
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
table.getSelectionModel().getSelectedItems().addListener((Observable observable) -> {
//keep the selectedEventsIDs in sync with the table's selection model, via getRepresentitiveEventID().
selectedEventIDs.setAll(table.getSelectionModel().getSelectedItems().stream()
.filter(Objects::nonNull)
.map(CombinedEvent::getRepresentativeEventID)
.collect(Collectors.toSet()));
});
}
/**
* Clear all the events out of the table.
*/
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
void clear() {
table.getItems().clear();
}
/**
* Set the Collection of CombinedEvents to show in the table.
*
* @param events The Collection of events to sho in the table.
*/
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
void setCombinedEvents(Collection<CombinedEvent> events) {
table.getItems().setAll(events);
}
/**
* Get an ObservableList of IDs of events that are selected in this table.
*
* @return An ObservableList of IDs of events that are selected in this
* table.
*/
ObservableList<Long> getSelectedEventIDs() {
return selectedEventIDs;
}
private static final Image HASH_HIT = new Image("/org/sleuthkit/autopsy/images/hashset_hits.png"); // NON-NLS
private static final Image TAG = new Image("/org/sleuthkit/autopsy/images/green-tag-icon-16.png"); // NON-NLS
private static final Image PIN = new Image("/org/sleuthkit/autopsy/timeline/images/marker--plus.png"); // NON-NLS
private static final Image UNPIN = new Image("/org/sleuthkit/autopsy/timeline/images/marker--minus.png"); // NON-NLS
private class TaggedCell extends EventTableCell {
TaggedCell() {
setAlignment(Pos.CENTER);
}
@NbBundle.Messages({
"ListTimeline.taggedTooltip.error=There was a problem getting the tag names for the selected event."})
@Override
protected void updateItem(CombinedEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || (getEvent().isTagged() == false)) {
setGraphic(null);
setTooltip(null);
} else {
setGraphic(new ImageView(TAG));
SortedSet<String> tagNames = new TreeSet<>();
try {
AbstractFile abstractFileById = sleuthkitCase.getAbstractFileById(getEvent().getFileID());
tagsManager.getContentTagsByContent(abstractFileById).stream()
.map(tag -> tag.getName().getDisplayName())
.forEach(tagNames::add);
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Failed to lookup tags for obj id " + getEvent().getFileID(), ex);
Platform.runLater(() -> {
Notifications.create()
.owner(getScene().getWindow())
.text(Bundle.ListTimeline_taggedTooltip_error())
.showError();
});
}
getEvent().getArtifactID().ifPresent(artifactID -> {
try {
BlackboardArtifact artifact = sleuthkitCase.getBlackboardArtifact(artifactID);
tagsManager.getBlackboardArtifactTagsByArtifact(artifact).stream()
.map(tag -> tag.getName().getDisplayName())
.forEach(tagNames::add);
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Failed to lookup tags for artifact id " + artifactID, ex);
Platform.runLater(() -> {
Notifications.create()
.owner(getScene().getWindow())
.text(Bundle.ListTimeline_taggedTooltip_error())
.showError();
});
}
});
setTooltip(new Tooltip("Tags: \n" + String.join("\n", tagNames)));
}
}
}
/**
* TableCell to show the hash hits if any associated with the file backing
* an event.
*/
private class HashHitCell extends EventTableCell {
HashHitCell() {
setAlignment(Pos.CENTER);
}
@NbBundle.Messages({
"ListTimeline.hashHitTooltip.error=There was a problem getting the hash set names for the selected event."})
@Override
protected void updateItem(CombinedEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || (getEvent().isHashHit() == false)) {
setGraphic(null);
setTooltip(null);
} else {
setGraphic(new ImageView(HASH_HIT));
try {
Set<String> hashSetNames = new TreeSet<>(sleuthkitCase.getAbstractFileById(getEvent().getFileID()).getHashSetNames());
setTooltip(new Tooltip("Hash Sets: \n" + String.join("\n", hashSetNames)));
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Failed to lookup hash set names for obj id " + getEvent().getFileID(), ex);
Platform.runLater(() -> {
Notifications.create()
.owner(getScene().getWindow())
.text(Bundle.ListTimeline_hashHitTooltip_error())
.showError();
});
}
}
}
}
/**
* Get an ObservableList of combined events that are selected in this table.
*
* @return An ObservableList of combined events that are selected in this
* table.
*/
ObservableList<CombinedEvent> getSelectedEvents() {
return table.getSelectionModel().getSelectedItems();
}
/**
* Set the combined events that are selected in this view.
*
* @param selectedEvents The events that should be selected.
*/
void selectEvents(Collection<CombinedEvent> selectedEvents) {
CombinedEvent firstSelected = selectedEvents.stream().min(Comparator.comparing(CombinedEvent::getStartMillis)).orElse(null);
table.getSelectionModel().clearSelection();
table.scrollTo(firstSelected);
selectedEvents.forEach(table.getSelectionModel()::select);
table.requestFocus();
}
/**
* TableCell to show the (sub) type of an event.
*/
private class EventTypeCell extends EventTableCell {
@Override
protected void updateItem(CombinedEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
} else {
if (item.getEventTypes().stream().allMatch(eventType -> eventType instanceof FileSystemTypes)) {
String s = "";
for (FileSystemTypes type : Arrays.asList(FileSystemTypes.FILE_MODIFIED, FileSystemTypes.FILE_ACCESSED, FileSystemTypes.FILE_CHANGED, FileSystemTypes.FILE_CREATED)) {
if (item.getEventTypes().contains(type)) {
switch (type) {
case FILE_MODIFIED:
s += "M";
break;
case FILE_ACCESSED:
s += "A";
break;
case FILE_CREATED:
s += "B";
break;
case FILE_CHANGED:
s += "C";
break;
default:
throw new UnsupportedOperationException("Unknown FileSystemType: " + type.name());
}
} else {
s += "_";
}
}
setText(s);
setGraphic(new ImageView(BaseTypes.FILE_SYSTEM.getFXImage()));
} else {
setText(Iterables.getOnlyElement(item.getEventTypes()).getDisplayName());
setGraphic(new ImageView(Iterables.getOnlyElement(item.getEventTypes()).getFXImage()));
};
}
}
}
/**
* TableCell to show text derived from a SingleEvent by the given Function.
*/
private class TextEventTableCell extends EventTableCell {
private final Function<SingleEvent, String> textSupplier;
/**
* Constructor
*
* @param textSupplier Function that takes a SingleEvent and produces a
* String to show in this TableCell.
*/
TextEventTableCell(Function<SingleEvent, String> textSupplier) {
this.textSupplier = textSupplier;
setTextOverrun(OverrunStyle.CENTER_ELLIPSIS);
setEllipsisString(" ... ");
}
@Override
protected void updateItem(CombinedEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
} else {
setText(textSupplier.apply(getEvent()));
}
}
}
/**
* Base class for TableCells that represent a MergedEvent by way of a
* representative SingleEvent.
*/
private abstract class EventTableCell extends TableCell<CombinedEvent, CombinedEvent> {
private SingleEvent event;
/**
* Get the representative SingleEvent for this cell.
*
* @return The representative SingleEvent for this cell.
*/
SingleEvent getEvent() {
return event;
}
@Override
protected void updateItem(CombinedEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
event = null;
} else {
//stash the event in the cell for derived classed to use.
event = controller.getEventsModel().getEventById(item.getRepresentativeEventID());
}
}
}
/**
* TableRow that adds a right-click context menu.
*/
private class EventRow extends TableRow<CombinedEvent> {
private SingleEvent event;
/**
* Get the representative SingleEvent for this row .
*
* @return The representative SingleEvent for this row .
*/
SingleEvent getEvent() {
return event;
}
@NbBundle.Messages({
"ListChart.errorMsg=There was a problem getting the content for the selected event."})
@Override
protected void updateItem(CombinedEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
event = null;
} else {
event = controller.getEventsModel().getEventById(item.getRepresentativeEventID());
setOnContextMenuRequested(contextMenuEvent -> {
//make a new context menu on each request in order to include uptodate tag names and hash sets
try {
EventNode node = EventNode.createEventNode(item.getRepresentativeEventID(), controller.getEventsModel());
List<MenuItem> menuItems = new ArrayList<>();
//for each actions avaialable on node, make a menu item.
for (Action action : node.getActions(false)) {
if (action == null) {
// swing/netbeans uses null action to represent separator in menu
menuItems.add(new SeparatorMenuItem());
} else {
String actionName = Objects.toString(action.getValue(Action.NAME));
//for now, suppress properties and tools actions, by ignoring them
if (Arrays.asList("&Properties", "Tools").contains(actionName) == false) {
if (action instanceof Presenter.Popup) {
/*
* If the action is really the root of a
* set of actions (eg, tagging). Make a
* menu that parallels the action's
* menu.
*/
JMenuItem submenu = ((Presenter.Popup) action).getPopupPresenter();
menuItems.add(SwingFXMenuUtils.createFXMenu(submenu));
} else {
menuItems.add(SwingFXMenuUtils.createFXMenu(new Actions.MenuItem(action, false)));
}
}
}
};
//show new context menu.
new ContextMenu(menuItems.toArray(new MenuItem[menuItems.size()]))
.show(this, contextMenuEvent.getScreenX(), contextMenuEvent.getScreenY());
} catch (IllegalStateException ex) {
//Since the case is closed, the user probably doesn't care about this, just log it as a precaution.
LOGGER.log(Level.SEVERE, "There was no case open to lookup the Sleuthkit object backing a SingleEvent.", ex); // NON-NLS
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Failed to lookup Sleuthkit object backing a SingleEvent.", ex); // NON-NLS
Platform.runLater(() -> {
Notifications.create()
.owner(getScene().getWindow())
.text(Bundle.ListChart_errorMsg())
.showError();
});
}
});
}
}
}
}
| Core/src/org/sleuthkit/autopsy/timeline/ui/listvew/ListTimeline.java | /*
* Autopsy Forensic Browser
*
* Copyright 2011-2016 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.timeline.ui.listvew;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Level;
import javafx.application.Platform;
import javafx.beans.Observable;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.OverrunStyle;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.util.Callback;
import javax.swing.Action;
import javax.swing.JMenuItem;
import org.controlsfx.control.Notifications;
import org.openide.awt.Actions;
import org.openide.util.NbBundle;
import org.openide.util.actions.Presenter;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.ThreadConfined;
import org.sleuthkit.autopsy.timeline.FXMLConstructor;
import org.sleuthkit.autopsy.timeline.TimeLineController;
import org.sleuthkit.autopsy.timeline.datamodel.CombinedEvent;
import org.sleuthkit.autopsy.timeline.datamodel.SingleEvent;
import org.sleuthkit.autopsy.timeline.datamodel.eventtype.BaseTypes;
import org.sleuthkit.autopsy.timeline.datamodel.eventtype.FileSystemTypes;
import org.sleuthkit.autopsy.timeline.explorernodes.EventNode;
import org.sleuthkit.autopsy.timeline.zooming.DescriptionLoD;
import org.sleuthkit.datamodel.TskCoreException;
/**
* The inner component that makes up the List view. Manages the TableView.
*/
class ListTimeline extends BorderPane {
private static final Logger LOGGER = Logger.getLogger(ListTimeline.class.getName());
/**
* call-back used to wrap the CombinedEvent in a ObservableValue
*/
private static final Callback<TableColumn.CellDataFeatures<CombinedEvent, CombinedEvent>, ObservableValue<CombinedEvent>> CELL_VALUE_FACTORY = param -> new SimpleObjectProperty<>(param.getValue());
@FXML
private Label eventCountLabel;
@FXML
private TableView<CombinedEvent> table;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> idColumn;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> dateTimeColumn;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> descriptionColumn;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> typeColumn;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> knownColumn;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> taggedColumn;
@FXML
private TableColumn<CombinedEvent, CombinedEvent> hashHitColumn;
private final TimeLineController controller;
/**
* Observable list used to track selected events.
*/
private final ObservableList<Long> selectedEventIDs = FXCollections.observableArrayList();
/**
* Constructor
*
* @param controller The controller for this timeline
*/
ListTimeline(TimeLineController controller) {
this.controller = controller;
FXMLConstructor.construct(this, ListTimeline.class, "ListTimeline.fxml");
}
@FXML
@NbBundle.Messages({
"# {0} - the number of events",
"ListTimeline.eventCountLabel.text={0} events"})
void initialize() {
assert eventCountLabel != null : "fx:id=\"eventCountLabel\" was not injected: check your FXML file 'ListViewPane.fxml'.";
assert table != null : "fx:id=\"table\" was not injected: check your FXML file 'ListViewPane.fxml'.";
assert idColumn != null : "fx:id=\"idColumn\" was not injected: check your FXML file 'ListViewPane.fxml'.";
assert dateTimeColumn != null : "fx:id=\"dateTimeColumn\" was not injected: check your FXML file 'ListViewPane.fxml'.";
assert descriptionColumn != null : "fx:id=\"descriptionColumn\" was not injected: check your FXML file 'ListViewPane.fxml'.";
assert typeColumn != null : "fx:id=\"typeColumn\" was not injected: check your FXML file 'ListViewPane.fxml'.";
assert knownColumn != null : "fx:id=\"knownColumn\" was not injected: check your FXML file 'ListViewPane.fxml'.";
//override default row with one that provides context menus
table.setRowFactory(tableView -> new EventRow());
//remove idColumn (can be restored for debugging).
table.getColumns().remove(idColumn);
//// set up cell and cell-value factories for columns
dateTimeColumn.setCellValueFactory(CELL_VALUE_FACTORY);
dateTimeColumn.setCellFactory(col -> new TextEventTableCell(singleEvent ->
TimeLineController.getZonedFormatter().print(singleEvent.getStartMillis())));
descriptionColumn.setCellValueFactory(CELL_VALUE_FACTORY);
descriptionColumn.setCellFactory(col -> new TextEventTableCell(singleEvent ->
singleEvent.getDescription(DescriptionLoD.FULL)));
typeColumn.setCellValueFactory(CELL_VALUE_FACTORY);
typeColumn.setCellFactory(col -> new EventTypeCell());
knownColumn.setCellValueFactory(CELL_VALUE_FACTORY);
knownColumn.setCellFactory(col -> new TextEventTableCell(singleEvent ->
singleEvent.getKnown().getName()));
taggedColumn.setCellValueFactory(CELL_VALUE_FACTORY);
taggedColumn.setCellFactory(col -> new TaggedCell());
hashHitColumn.setCellValueFactory(CELL_VALUE_FACTORY);
hashHitColumn.setCellFactory(col -> new HashHitCell());
//bind event count label to number of items in the table
eventCountLabel.textProperty().bind(new StringBinding() {
{
bind(table.getItems());
}
@Override
protected String computeValue() {
return Bundle.ListTimeline_eventCountLabel_text(table.getItems().size());
}
});
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
table.getSelectionModel().getSelectedItems().addListener((Observable observable) -> {
//keep the selectedEventsIDs in sync with the table's selection model, via getRepresentitiveEventID().
selectedEventIDs.setAll(FluentIterable.from(table.getSelectionModel().getSelectedItems())
.filter(Objects::nonNull)
.transform(CombinedEvent::getRepresentativeEventID)
.toSet());
});
}
/**
* Clear all the events out of the table.
*/
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
void clear() {
table.getItems().clear();
}
/**
* Set the Collection of CombinedEvents to show in the table.
*
* @param events The Collection of events to sho in the table.
*/
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
void setCombinedEvents(Collection<CombinedEvent> events) {
table.getItems().setAll(events);
}
/**
* Get an ObservableList of IDs of events that are selected in this table.
*
* @return An ObservableList of IDs of events that are selected in this
* table.
*/
ObservableList<Long> getSelectedEventIDs() {
return selectedEventIDs;
}
private static final Image HASH_HIT = new Image("/org/sleuthkit/autopsy/images/hashset_hits.png"); // NON-NLS
private static final Image TAG = new Image("/org/sleuthkit/autopsy/images/green-tag-icon-16.png"); // NON-NLS
private static final Image PIN = new Image("/org/sleuthkit/autopsy/timeline/images/marker--plus.png"); // NON-NLS
private static final Image UNPIN = new Image("/org/sleuthkit/autopsy/timeline/images/marker--minus.png"); // NON-NLS
private class TaggedCell extends EventTableCell {
@Override
protected void updateItem(CombinedEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || (getEvent().isTagged() == false)) {
setGraphic(null);
setTooltip(null);
} else {
setGraphic(new ImageView(TAG));
}
}
}
/**
* TableCell to show the hash hits if any associated with the file backing
* an event.
*/
private class HashHitCell extends EventTableCell {
@NbBundle.Messages({
"ListTimeline.hashHitTooltip.error=There was a problem getting the hash set names for the selected event."})
@Override
protected void updateItem(CombinedEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || (getEvent().isHashHit() == false)) {
setGraphic(null);
setTooltip(null);
} else {
setGraphic(new ImageView(HASH_HIT));
try {
Set<String> hashSetNames = controller.getAutopsyCase().getSleuthkitCase().getAbstractFileById(getEvent().getFileID()).getHashSetNames();
setTooltip(new Tooltip("Hash Sets: \n" + String.join("\n", hashSetNames)));
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Failed to lookup hash set names for obj id " + getEvent().getFileID(), ex);
Platform.runLater(() -> {
Notifications.create()
.owner(getScene().getWindow())
.text(Bundle.ListTimeline_hashHitTooltip_error())
.showError();
});
}
}
}
}
/**
* Get an ObservableList of combined events that are selected in this table.
*
* @return An ObservableList of combined events that are selected in this
* table.
*/
ObservableList<CombinedEvent> getSelectedEvents() {
return table.getSelectionModel().getSelectedItems();
}
/**
* Set the combined events that are selected in this view.
*
* @param selectedEvents The events that should be selected.
*/
void selectEvents(Collection<CombinedEvent> selectedEvents) {
CombinedEvent firstSelected = selectedEvents.stream().min(Comparator.comparing(CombinedEvent::getStartMillis)).orElse(null);
table.getSelectionModel().clearSelection();
table.scrollTo(firstSelected);
selectedEvents.forEach(table.getSelectionModel()::select);
table.requestFocus();
}
/**
* TableCell to show the (sub) type of an event.
*/
private class EventTypeCell extends EventTableCell {
@Override
protected void updateItem(CombinedEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
} else {
if (item.getEventTypes().stream().allMatch(eventType -> eventType instanceof FileSystemTypes)) {
String s = "";
for (FileSystemTypes type : Arrays.asList(FileSystemTypes.FILE_MODIFIED, FileSystemTypes.FILE_ACCESSED, FileSystemTypes.FILE_CHANGED, FileSystemTypes.FILE_CREATED)) {
if (item.getEventTypes().contains(type)) {
switch (type) {
case FILE_MODIFIED:
s += "M";
break;
case FILE_ACCESSED:
s += "A";
break;
case FILE_CREATED:
s += "B";
break;
case FILE_CHANGED:
s += "C";
break;
default:
throw new UnsupportedOperationException("Unknown FileSystemType: " + type.name());
}
} else {
s += "_";
}
}
setText(s);
setGraphic(new ImageView(BaseTypes.FILE_SYSTEM.getFXImage()));
} else {
setText(Iterables.getOnlyElement(item.getEventTypes()).getDisplayName());
setGraphic(new ImageView(Iterables.getOnlyElement(item.getEventTypes()).getFXImage()));
};
}
}
}
/**
* TableCell to show text derived from a SingleEvent by the given Function.
*/
private class TextEventTableCell extends EventTableCell {
private final Function<SingleEvent, String> textSupplier;
/**
* Constructor
*
* @param textSupplier Function that takes a SingleEvent and produces a
* String to show in this TableCell.
*/
TextEventTableCell(Function<SingleEvent, String> textSupplier) {
this.textSupplier = textSupplier;
setTextOverrun(OverrunStyle.CENTER_ELLIPSIS);
setEllipsisString(" ... ");
}
@Override
protected void updateItem(CombinedEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
} else {
setText(textSupplier.apply(getEvent()));
}
}
}
/**
* Base class for TableCells that represent a MergedEvent by way of a
* representative SingleEvent.
*/
private abstract class EventTableCell extends TableCell<CombinedEvent, CombinedEvent> {
private SingleEvent event;
/**
* Get the representative SingleEvent for this cell.
*
* @return The representative SingleEvent for this cell.
*/
SingleEvent getEvent() {
return event;
}
@Override
protected void updateItem(CombinedEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
event = null;
} else {
//stash the event in the cell for derived classed to use.
event = controller.getEventsModel().getEventById(item.getRepresentativeEventID());
}
}
}
/**
* TableRow that adds a right-click context menu.
*/
private class EventRow extends TableRow<CombinedEvent> {
private SingleEvent event;
/**
* Get the representative SingleEvent for this row .
*
* @return The representative SingleEvent for this row .
*/
SingleEvent getEvent() {
return event;
}
@NbBundle.Messages({
"ListChart.errorMsg=There was a problem getting the content for the selected event."})
@Override
protected void updateItem(CombinedEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
event = null;
} else {
event = controller.getEventsModel().getEventById(item.getRepresentativeEventID());
setOnContextMenuRequested(contextMenuEvent -> {
//make a new context menu on each request in order to include uptodate tag names and hash sets
try {
EventNode node = EventNode.createEventNode(item.getRepresentativeEventID(), controller.getEventsModel());
List<MenuItem> menuItems = new ArrayList<>();
//for each actions avaialable on node, make a menu item.
for (Action action : node.getActions(false)) {
if (action == null) {
// swing/netbeans uses null action to represent separator in menu
menuItems.add(new SeparatorMenuItem());
} else {
String actionName = Objects.toString(action.getValue(Action.NAME));
//for now, suppress properties and tools actions, by ignoring them
if (Arrays.asList("&Properties", "Tools").contains(actionName) == false) {
if (action instanceof Presenter.Popup) {
/*
* If the action is really the root of a
* set of actions (eg, tagging). Make a
* menu that parallels the action's
* menu.
*/
JMenuItem submenu = ((Presenter.Popup) action).getPopupPresenter();
menuItems.add(SwingFXMenuUtils.createFXMenu(submenu));
} else {
menuItems.add(SwingFXMenuUtils.createFXMenu(new Actions.MenuItem(action, false)));
}
}
}
};
//show new context menu.
new ContextMenu(menuItems.toArray(new MenuItem[menuItems.size()]))
.show(this, contextMenuEvent.getScreenX(), contextMenuEvent.getScreenY());
} catch (IllegalStateException ex) {
//Since the case is closed, the user probably doesn't care about this, just log it as a precaution.
LOGGER.log(Level.SEVERE, "There was no case open to lookup the Sleuthkit object backing a SingleEvent.", ex); // NON-NLS
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Failed to lookup Sleuthkit object backing a SingleEvent.", ex); // NON-NLS
Platform.runLater(() -> {
Notifications.create()
.owner(getScene().getWindow())
.text(Bundle.ListChart_errorMsg())
.showError();
});
}
});
}
}
}
}
| add tooltips to Tag column
| Core/src/org/sleuthkit/autopsy/timeline/ui/listvew/ListTimeline.java | add tooltips to Tag column | <ide><path>ore/src/org/sleuthkit/autopsy/timeline/ui/listvew/ListTimeline.java
<ide> */
<ide> package org.sleuthkit.autopsy.timeline.ui.listvew;
<ide>
<del>import com.google.common.collect.FluentIterable;
<ide> import com.google.common.collect.Iterables;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide> import java.util.Objects;
<ide> import java.util.Set;
<add>import java.util.SortedSet;
<add>import java.util.TreeSet;
<ide> import java.util.function.Function;
<ide> import java.util.logging.Level;
<add>import java.util.stream.Collectors;
<ide> import javafx.application.Platform;
<ide> import javafx.beans.Observable;
<ide> import javafx.beans.binding.StringBinding;
<ide> import javafx.collections.FXCollections;
<ide> import javafx.collections.ObservableList;
<ide> import javafx.fxml.FXML;
<add>import javafx.geometry.Pos;
<ide> import javafx.scene.control.ContextMenu;
<ide> import javafx.scene.control.Label;
<ide> import javafx.scene.control.MenuItem;
<ide> import org.openide.awt.Actions;
<ide> import org.openide.util.NbBundle;
<ide> import org.openide.util.actions.Presenter;
<add>import org.sleuthkit.autopsy.casemodule.services.TagsManager;
<ide> import org.sleuthkit.autopsy.coreutils.Logger;
<ide> import org.sleuthkit.autopsy.coreutils.ThreadConfined;
<ide> import org.sleuthkit.autopsy.timeline.FXMLConstructor;
<ide> import org.sleuthkit.autopsy.timeline.datamodel.eventtype.FileSystemTypes;
<ide> import org.sleuthkit.autopsy.timeline.explorernodes.EventNode;
<ide> import org.sleuthkit.autopsy.timeline.zooming.DescriptionLoD;
<add>import org.sleuthkit.datamodel.AbstractFile;
<add>import org.sleuthkit.datamodel.BlackboardArtifact;
<add>import org.sleuthkit.datamodel.SleuthkitCase;
<ide> import org.sleuthkit.datamodel.TskCoreException;
<ide>
<ide> /**
<ide> * Observable list used to track selected events.
<ide> */
<ide> private final ObservableList<Long> selectedEventIDs = FXCollections.observableArrayList();
<add> private final SleuthkitCase sleuthkitCase;
<add> private final TagsManager tagsManager;
<ide>
<ide> /**
<ide> * Constructor
<ide> */
<ide> ListTimeline(TimeLineController controller) {
<ide> this.controller = controller;
<add> sleuthkitCase = controller.getAutopsyCase().getSleuthkitCase();
<add> tagsManager = controller.getAutopsyCase().getServices().getTagsManager();
<ide> FXMLConstructor.construct(this, ListTimeline.class, "ListTimeline.fxml");
<ide> }
<ide>
<ide> table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
<ide> table.getSelectionModel().getSelectedItems().addListener((Observable observable) -> {
<ide> //keep the selectedEventsIDs in sync with the table's selection model, via getRepresentitiveEventID().
<del> selectedEventIDs.setAll(FluentIterable.from(table.getSelectionModel().getSelectedItems())
<add> selectedEventIDs.setAll(table.getSelectionModel().getSelectedItems().stream()
<ide> .filter(Objects::nonNull)
<del> .transform(CombinedEvent::getRepresentativeEventID)
<del> .toSet());
<add> .map(CombinedEvent::getRepresentativeEventID)
<add> .collect(Collectors.toSet()));
<ide> });
<ide> }
<ide>
<ide>
<ide> private class TaggedCell extends EventTableCell {
<ide>
<add> TaggedCell() {
<add> setAlignment(Pos.CENTER);
<add> }
<add>
<add> @NbBundle.Messages({
<add> "ListTimeline.taggedTooltip.error=There was a problem getting the tag names for the selected event."})
<ide> @Override
<ide> protected void updateItem(CombinedEvent item, boolean empty) {
<ide> super.updateItem(item, empty);
<ide> setTooltip(null);
<ide> } else {
<ide> setGraphic(new ImageView(TAG));
<add> SortedSet<String> tagNames = new TreeSet<>();
<add> try {
<add> AbstractFile abstractFileById = sleuthkitCase.getAbstractFileById(getEvent().getFileID());
<add> tagsManager.getContentTagsByContent(abstractFileById).stream()
<add> .map(tag -> tag.getName().getDisplayName())
<add> .forEach(tagNames::add);
<add>
<add> } catch (TskCoreException ex) {
<add> LOGGER.log(Level.SEVERE, "Failed to lookup tags for obj id " + getEvent().getFileID(), ex);
<add> Platform.runLater(() -> {
<add> Notifications.create()
<add> .owner(getScene().getWindow())
<add> .text(Bundle.ListTimeline_taggedTooltip_error())
<add> .showError();
<add> });
<add> }
<add> getEvent().getArtifactID().ifPresent(artifactID -> {
<add> try {
<add> BlackboardArtifact artifact = sleuthkitCase.getBlackboardArtifact(artifactID);
<add> tagsManager.getBlackboardArtifactTagsByArtifact(artifact).stream()
<add> .map(tag -> tag.getName().getDisplayName())
<add> .forEach(tagNames::add);
<add> } catch (TskCoreException ex) {
<add> LOGGER.log(Level.SEVERE, "Failed to lookup tags for artifact id " + artifactID, ex);
<add> Platform.runLater(() -> {
<add> Notifications.create()
<add> .owner(getScene().getWindow())
<add> .text(Bundle.ListTimeline_taggedTooltip_error())
<add> .showError();
<add> });
<add> }
<add> });
<add>
<add> setTooltip(new Tooltip("Tags: \n" + String.join("\n", tagNames)));
<ide> }
<ide> }
<ide> }
<ide> * an event.
<ide> */
<ide> private class HashHitCell extends EventTableCell {
<add>
<add> HashHitCell() {
<add> setAlignment(Pos.CENTER);
<add> }
<ide>
<ide> @NbBundle.Messages({
<ide> "ListTimeline.hashHitTooltip.error=There was a problem getting the hash set names for the selected event."})
<ide> } else {
<ide> setGraphic(new ImageView(HASH_HIT));
<ide> try {
<del> Set<String> hashSetNames = controller.getAutopsyCase().getSleuthkitCase().getAbstractFileById(getEvent().getFileID()).getHashSetNames();
<add> Set<String> hashSetNames = new TreeSet<>(sleuthkitCase.getAbstractFileById(getEvent().getFileID()).getHashSetNames());
<add>
<ide> setTooltip(new Tooltip("Hash Sets: \n" + String.join("\n", hashSetNames)));
<ide> } catch (TskCoreException ex) {
<ide> LOGGER.log(Level.SEVERE, "Failed to lookup hash set names for obj id " + getEvent().getFileID(), ex); |
|
Java | apache-2.0 | f12a80ad3f1482fc6e7a74fc9bd420dadbb5e73f | 0 | isuru-c/LeakHawk,isuru-c/LeakHawk,isuru-c/LeakHawk,isuru-c/LeakHawk | /*
* Copyright 2017 SWIS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import classifiers.EvidenceModel;
import model.Post;
import db.DBConnection;
import db.DBHandle;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import weka.classifiers.Evaluation;
import weka.classifiers.bayes.NaiveBayesMultinomial;
import weka.classifiers.evaluation.ThresholdCurve;
import weka.core.Instances;
import weka.core.Utils;
import weka.core.converters.TextDirectoryLoader;
import weka.core.stemmers.SnowballStemmer;
import weka.core.stopwords.StopwordsHandler;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.StringToWordVector;
import weka.gui.visualize.PlotData2D;
import weka.gui.visualize.ThresholdVisualizePanel;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
/**
* Created by Isuru Chandima on 7/28/17.
*/
public class EvidenceClassifierBolt extends BaseRichBolt {
private OutputCollector collector;
private ArrayList<String> keyWordList1;
private ArrayList<String> keyWordList2;
private ArrayList<String> keyWordList3;
private ArrayList<String> keyWordList4;
private ArrayList<String> keyWordList5;
private ArrayList<String> keyWordList6;
private ArrayList<String> keyWordList7;
private ArrayList<String> keyWordList8;
private Connection connection;
private TextDirectoryLoader loader;
private Instances dataRaw;
private StringToWordVector filter;
private Instances dataFiltered;
private List<String> stopWordList;
private String regex;
private String regex1;
public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
collector = outputCollector;
loader = new TextDirectoryLoader();
stopWordList = Arrays.asList("a","about","above","after","again"," against","all","am","an","and","any","are","aren't","as","at","be","because","been","before","being","below","between","both","but","by","can't","cannot","could","couldn't","did","didn't","do","does","doesn't","doing","don't","down","during","each","few","for","from","further","had","hadn't","has","hasn't","have","haven't","having","he","he'd","he'll","he's","her","here","here's","hers","herself","him","himself","his","how","how's","i","i'd","i'll","i'm","i've","if","in","into","is","isn't","it","it's","its","itself","let's","me","more","most","mustn't","my","myself","no","nor","not","of","off","on","once","only","or","other","ought","our","ours","ourselves","out","over","own","same","shan't","she","she'd","she'll","she's","should","shouldn't","so","some","such","than","that","that's","the","their","theirs","them","themselves","then","there","there's","these","they","they'd","they'll","they're","they've","this","those","through","to","too","under","until","up","very","was","wasn't","we","we'd","we'll","we're","we've","were","weren't","what","what's","when","when's","where","where's","which","while","who","who's","whom","why","why's","with","won't","would","wouldn't","you","you'd","you'll","you're","you've","your","yours","yourself","yourselves");
regex = "[0-9]+";
regex1 = "[.,?!@#%;:'\"\\-]";
keyWordList1 = new ArrayList(Arrays.asList("Hacked", "leaked by", "Pwned by", "Doxed", "Ow3ned", "pawned by", "Server Rootéd", "#opSriLanka", "#OPlanka", "#anonymous", "Private key", "Password leak", "password dump", "credential leak", "credential dump", "Credit card", "Card dump ", " cc dump ", " credit_card", "card_dump", "working_card", "cc_dump", "skimmed", "card_hack", "sited hacked by", "websited hacked by", "website hacked by", "site hacked by", "websited hacked", "domain hack", "defaced", "leaked by", "site deface", "mass deface", "database dump", "database dumped", "db dumped", "db_dump", "db leak", "model base dump", "model base leak", "database hack", "db hack", "login dump", "DNS LeAkEd", "DNS fuck3d", "zone transfer", "DNS Enumeration", "Enumeration Attack", "cache snooping", "cache poisoning", "email hack", "emails hack", "emails leak,email leak", "email dump", "emails dump", "email dumps", "email-list", "leaked email,leaked emails", "email_hack"));
keyWordList2 = new ArrayList(Arrays.asList("dns-brute", "dnsrecon", "fierce", "Dnsdict6", "axfr", "SQLmap"));
keyWordList3 = new ArrayList(Arrays.asList("SQL_Injection", "SQLi", "SQL-i", "Blind SQL-i"));
keyWordList4 = new ArrayList(Arrays.asList("UGLegion", "RetrOHacK", "Anonymous", "AnonSec", "AnonGhost", "ANONYMOUSSRILANKA", "W3BD3F4C3R", "SLCYBERARMY", "DAVYJONES", "BLACKHATANON", "ANUARLINUX", "UGLEGION", "HUSSEIN98D", "We_Are_Anonymous", "We_do_not_Forget", "We_do_not_Forgive", "Laughing_at_your_security_since_2012", "AnonGhost_is_Everywhere"));
keyWordList5 = new ArrayList(Arrays.asList("Hacked", "leaked by", "Pwned by", "Doxed", "Ow3ned", "pawned by", "Server Rootéd", "#opSriLanka", "#OPlanka", "#anonymous", "Private key", "Password leak", "password dump", "credential leak", "credential dump", "Credit card", "Card dump ", " cc dump ", " credit_card", "card_dump", "working_card", "cc_dump", "skimmed", "card_hack", "sited hacked by", "websited hacked by", "website hacked by", "site hacked by", "websited hacked", "domain hack", "defaced", "leaked by", "site deface", "mass deface", "database dump", "database dumped", "db dumped", "db dump", "db leak", "model base dump", "model base leak", "database hack", "db hack", "login dump", "DNS LeAkEd", "DNS fuck3d", "zone transfer", "DNS Enumeration", "Enumeration Attack", "cache snooping", "cache poisoning", "email hack", "emails hack", "emails leak,email leak", "email dump", "emails dump", "email dumps", "email-list", "leaked email,leaked emails", "email_hack"));
keyWordList6 = new ArrayList(Arrays.asList("dns-brute", "dnsrecon", "fierce", "Dnsdict6", "axfr", "SQLmap"));
keyWordList7 = new ArrayList(Arrays.asList("SQL Injection", "SQLi", "SQL-i", "Blind SQL-i"));
keyWordList8 = new ArrayList(Arrays.asList("UGLegion", "RetrOHacK", "Anonymous", "AnonSec", "AnonGhost", "ANONYMOUSSRILANKA", "W3BD3F4C3R", "SLCYBERARMY", "DAVYJONES", "BLACKHATANON", "ANUARLINUX", "UGLEGION", "HUSSEIN98D", "We Are Anonymous", "We do not Forget, We do not Forgive", "Laughing at your security since 2012", "AnonGhost is Everywhere"));
try {
connection = DBConnection.getDBConnection().getConnection();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void execute(Tuple tuple) {
Post post = (Post)tuple.getValue(0);
EvidenceModel evidenceModel = new EvidenceModel();
post.setEvidenceModel(evidenceModel);
Boolean evidenceFound = isPassedEvidenceClassifier(post.getUser(), post.getTitle(), post.getPostText(), evidenceModel);
evidenceModel.setEvidenceFound(evidenceFound);
post.setEvidenceClassifierPassed();
collector.emit(tuple, new Values(post));
// Following line is used to make Context and Evidence classifiers run parallel.
//collector.emit("EvidenceClassifier-out", tuple, new Values(post));
collector.ack(tuple);
}
private boolean isPassedEvidenceClassifier(String user, String title, String post, EvidenceModel evidenceModel) {
title = title.toLowerCase();
post = post.toLowerCase();
boolean evidenceFound = false;
//#U1-USER: Does the user, seems suspicious?
//need to compare with the database - percentage
//#E1 SUBJECT:Is there any evidence of a hacking attack on the subject?
for (String i : keyWordList1) {
if (title.contains(i.toLowerCase())) {
evidenceModel.setClassifier1Passed(true);
evidenceFound = true;
}
}
try {
ResultSet data = DBHandle.getData(connection, "SELECT user FROM Incident");
while(data.next()){
String userFromDB = data.getString("user");
if (title.contains(userFromDB.toLowerCase())) {
evidenceModel.setClassifier1Passed(true);
evidenceFound = true;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
//#E2 SUBJECT:Are there any signs of usage of a security tool?
for (String i : keyWordList2) {
if (title.contains(i.toLowerCase())) {
evidenceModel.setClassifier2Passed(true);
evidenceFound = true;
}
}
//#E3 SUBJECT:Are there any signs of security vulnerability?
for (String i : keyWordList3) {
if (title.contains(i.toLowerCase())) {
evidenceModel.setClassifier3Passed(true);
evidenceFound = true;
}
}
//#E4 SUBJECT:Evidence of a Hacker involvement/Hacktivist movement?
for (String i : keyWordList4) {
if (title.contains(i.toLowerCase())) {
evidenceModel.setClassifier4Passed(true);
evidenceFound = true;
}
}
//#E5 BODY: Is there any evidence of a hacking attack in the body text?
for (String i : keyWordList5) {
if (post.contains(i.toLowerCase())) {
evidenceModel.setClassifier5Passed(true);
evidenceFound = true;
}
}
//#E6 BODY: Are there any signs of usage of a security tool in the body text?
for (String i : keyWordList6) {
if (post.contains(i.toLowerCase())) {
evidenceModel.setClassifier6Passed(true);
evidenceFound = true;
}
}
//#E7 BODY: Are there any signs of security vulnerability in the body text?
for (String i : keyWordList7) {
if (post.contains(i.toLowerCase())) {
evidenceModel.setClassifier7Passed(true);
evidenceFound = true;
}
}
//#E8 BODY: Are there any signs of security vulnerability in the body text?
for (String i : keyWordList8) {
if (post.toLowerCase().contains(i.toLowerCase())) {
evidenceModel.setClassifier8Passed(true);
evidenceFound = true;
}
}
return evidenceFound;
}
private void buildClassifier() {
try{
loader.setDirectory(new File("~/IdeaProjects/LeakHawk/dataset/"));
dataRaw = loader.getDataSet();
filter = new StringToWordVector();
StopwordsHandler stopwordsHandler = new StopwordsHandler() {
Matcher matcher;
//@Override
public boolean isStopword(String s) {
if(stopWordList.contains(s) || s.length()<3 || s.matches(regex1) || s.matches(regex)) //matcher == p.matcher(s)
return true;
else return false;
}
};
filter.setStopwordsHandler(stopwordsHandler);
SnowballStemmer stemmer = new SnowballStemmer();
filter.setStemmer(stemmer);
filter.setLowerCaseTokens(true);
filter.setTFTransform(true);
filter.setIDFTransform(true);
filter.setInputFormat(dataRaw);
dataFiltered = Filter.useFilter(dataRaw, filter);
System.out.println("\n\nFiltered data:\n\n" + dataFiltered);
NaiveBayesMultinomial classifier = new NaiveBayesMultinomial();
classifier.buildClassifier(dataFiltered);
//System.out.println("\n\nClassifier model:\n\n" + classifier);
Evaluation evaluation = new Evaluation(dataFiltered);
evaluation.crossValidateModel(classifier,dataFiltered,10,new Random());
System.out.println(evaluation.toSummaryString()+evaluation.toMatrixString());
// generate curve
/* ThresholdCurve tc = new ThresholdCurve();
int classIndex = 0;
Instances result = tc.getCurve(evaluation.predictions(), classIndex);
// plot curve
ThresholdVisualizePanel vmc = new ThresholdVisualizePanel();
vmc.setROCString("(Area under ROC = " +
Utils.doubleToString(tc.getROCArea(result), 4) + ")");
vmc.setName(result.relationName());
PlotData2D tempd = new PlotData2D(result);
tempd.setPlotName(result.relationName());
tempd.addInstanceNumberAttribute();
// specify which points are connected
boolean[] cp = new boolean[result.numInstances()];
for (int n = 1; n < cp.length; n++)
cp[n] = true;
tempd.setConnectPoints(cp);
// add plot
vmc.addPlot(tempd);
// display curve
String plotName = vmc.getName();
final javax.swing.JFrame jf =
new javax.swing.JFrame("Weka Classifier Visualize: "+plotName);
jf.setSize(500,400);
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(vmc, BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
}
});
jf.setVisible(true);
*/
}
catch (IOException ex){
System.out.println("IOException");
}catch(Exception ex1){
}
}
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
outputFieldsDeclarer.declare(new Fields("post"));
// Following line is used to make Context and Evidence classifiers run parallel.
// outputFieldsDeclarer.declareStream("EvidenceClassifier-out", new Fields("post"));
}
}
| src/main/java/EvidenceClassifierBolt.java | /*
* Copyright 2017 SWIS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import classifiers.EvidenceModel;
import model.Post;
import db.DBConnection;
import db.DBHandle;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import weka.classifiers.Evaluation;
import weka.classifiers.bayes.NaiveBayesMultinomial;
import weka.classifiers.evaluation.ThresholdCurve;
import weka.core.Instances;
import weka.core.Utils;
import weka.core.converters.TextDirectoryLoader;
import weka.core.stemmers.SnowballStemmer;
import weka.core.stopwords.StopwordsHandler;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.StringToWordVector;
import weka.gui.visualize.PlotData2D;
import weka.gui.visualize.ThresholdVisualizePanel;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
/**
* Created by Isuru Chandima on 7/28/17.
*/
public class EvidenceClassifierBolt extends BaseRichBolt {
private OutputCollector collector;
private ArrayList<String> keyWordList1;
private ArrayList<String> keyWordList2;
private ArrayList<String> keyWordList3;
private ArrayList<String> keyWordList4;
private ArrayList<String> keyWordList5;
private ArrayList<String> keyWordList6;
private ArrayList<String> keyWordList7;
private ArrayList<String> keyWordList8;
private Connection connection;
private TextDirectoryLoader loader;
private Instances dataRaw;
private StringToWordVector filter;
private Instances dataFiltered;
private List<String> stopWordList;
private String regex;
private String regex1;
public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
collector = outputCollector;
loader = new TextDirectoryLoader();
stopWordList = Arrays.asList("a","about","above","after","again"," against","all","am","an","and","any","are","aren't","as","at","be","because","been","before","being","below","between","both","but","by","can't","cannot","could","couldn't","did","didn't","do","does","doesn't","doing","don't","down","during","each","few","for","from","further","had","hadn't","has","hasn't","have","haven't","having","he","he'd","he'll","he's","her","here","here's","hers","herself","him","himself","his","how","how's","i","i'd","i'll","i'm","i've","if","in","into","is","isn't","it","it's","its","itself","let's","me","more","most","mustn't","my","myself","no","nor","not","of","off","on","once","only","or","other","ought","our","ours","ourselves","out","over","own","same","shan't","she","she'd","she'll","she's","should","shouldn't","so","some","such","than","that","that's","the","their","theirs","them","themselves","then","there","there's","these","they","they'd","they'll","they're","they've","this","those","through","to","too","under","until","up","very","was","wasn't","we","we'd","we'll","we're","we've","were","weren't","what","what's","when","when's","where","where's","which","while","who","who's","whom","why","why's","with","won't","would","wouldn't","you","you'd","you'll","you're","you've","your","yours","yourself","yourselves");
regex = "[0-9]+";
regex1 = "[.,?!@#%;:'\"\\-]";
keyWordList1 = new ArrayList(Arrays.asList("Hacked", "leaked by", "Pwned by", "Doxed", "Ow3ned", "pawned by", "Server Rootéd", "#opSriLanka", "#OPlanka", "#anonymous", "Private key", "Password leak", "password dump", "credential leak", "credential dump", "Credit card", "Card dump ", " cc dump ", " credit_card", "card_dump", "working_card", "cc_dump", "skimmed", "card_hack", "sited hacked by", "websited hacked by", "website hacked by", "site hacked by", "websited hacked", "domain hack", "defaced", "leaked by", "site deface", "mass deface", "database dump", "database dumped", "db dumped", "db_dump", "db leak", "model base dump", "model base leak", "database hack", "db hack", "login dump", "DNS LeAkEd", "DNS fuck3d", "zone transfer", "DNS Enumeration", "Enumeration Attack", "cache snooping", "cache poisoning", "email hack", "emails hack", "emails leak,email leak", "email dump", "emails dump", "email dumps", "email-list", "leaked email,leaked emails", "email_hack"));
keyWordList2 = new ArrayList(Arrays.asList("dns-brute", "dnsrecon", "fierce", "Dnsdict6", "axfr", "SQLmap"));
keyWordList3 = new ArrayList(Arrays.asList("SQL_Injection", "SQLi", "SQL-i", "Blind SQL-i"));
keyWordList4 = new ArrayList(Arrays.asList("UGLegion", "RetrOHacK", "Anonymous", "AnonSec", "AnonGhost", "ANONYMOUSSRILANKA", "W3BD3F4C3R", "SLCYBERARMY", "DAVYJONES", "BLACKHATANON", "ANUARLINUX", "UGLEGION", "HUSSEIN98D", "We_Are_Anonymous", "We_do_not_Forget", "We_do_not_Forgive", "Laughing_at_your_security_since_2012", "AnonGhost_is_Everywhere"));
keyWordList5 = new ArrayList(Arrays.asList("Hacked", "leaked by", "Pwned by", "Doxed", "Ow3ned", "pawned by", "Server Rootéd", "#opSriLanka", "#OPlanka", "#anonymous", "Private key", "Password leak", "password dump", "credential leak", "credential dump", "Credit card", "Card dump ", " cc dump ", " credit_card", "card_dump", "working_card", "cc_dump", "skimmed", "card_hack", "sited hacked by", "websited hacked by", "website hacked by", "site hacked by", "websited hacked", "domain hack", "defaced", "leaked by", "site deface", "mass deface", "database dump", "database dumped", "db dumped", "db dump", "db leak", "model base dump", "model base leak", "database hack", "db hack", "login dump", "DNS LeAkEd", "DNS fuck3d", "zone transfer", "DNS Enumeration", "Enumeration Attack", "cache snooping", "cache poisoning", "email hack", "emails hack", "emails leak,email leak", "email dump", "emails dump", "email dumps", "email-list", "leaked email,leaked emails", "email_hack"));
keyWordList6 = new ArrayList(Arrays.asList("dns-brute", "dnsrecon", "fierce", "Dnsdict6", "axfr", "SQLmap"));
keyWordList7 = new ArrayList(Arrays.asList("SQL Injection", "SQLi", "SQL-i", "Blind SQL-i"));
keyWordList8 = new ArrayList(Arrays.asList("UGLegion", "RetrOHacK", "Anonymous", "AnonSec", "AnonGhost", "ANONYMOUSSRILANKA", "W3BD3F4C3R", "SLCYBERARMY", "DAVYJONES", "BLACKHATANON", "ANUARLINUX", "UGLEGION", "HUSSEIN98D", "We Are Anonymous", "We do not Forget, We do not Forgive", "Laughing at your security since 2012", "AnonGhost is Everywhere"));
try {
connection = DBConnection.getDBConnection().getConnection();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void execute(Tuple tuple) {
Post post = (Post)tuple.getValue(0);
EvidenceModel evidenceModel = new EvidenceModel();
post.setEvidenceModel(evidenceModel);
Boolean evidenceFound = isPassedEvidenceClassifier(post.getUser(), post.getTitle(), post.getPostText(), evidenceModel);
evidenceModel.setEvidenceFound(evidenceFound);
post.setEvidenceClassifierPassed();
collector.emit(tuple, new Values(post));
// Following line is used to make Context and Evidence classifiers run parallel.
//collector.emit("EvidenceClassifier-out", tuple, new Values(post));
collector.ack(tuple);
}
private boolean isPassedEvidenceClassifier(String user, String title, String post, EvidenceModel evidenceModel) {
title = title.toLowerCase();
post = post.toLowerCase();
boolean evidenceFound = false;
//#U1-USER: Does the user, seems suspicious?
//need to compare with the database - percentage
//#E1 SUBJECT:Is there any evidence of a hacking attack on the subject?
for (String i : keyWordList1) {
if (title.contains(i.toLowerCase())) {
evidenceModel.setClassifier1Passed(true);
evidenceFound = true;
}
}
try {
ResultSet data = DBHandle.getData(connection, "SELECT user FROM Incident");
while(data.next()){
String userFromDB = data.getString("user");
if (title.contains(userFromDB.toLowerCase())) {
evidenceModel.setClassifier1Passed(true);
evidenceFound = true;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
//#E2 SUBJECT:Are there any signs of usage of a security tool?
for (String i : keyWordList2) {
if (title.contains(i.toLowerCase())) {
evidenceModel.setClassifier2Passed(true);
evidenceFound = true;
}
}
//#E3 SUBJECT:Are there any signs of security vulnerability?
for (String i : keyWordList3) {
if (title.contains(i.toLowerCase())) {
evidenceModel.setClassifier3Passed(true);
evidenceFound = true;
}
}
//#E4 SUBJECT:Evidence of a Hacker involvement/Hacktivist movement?
for (String i : keyWordList4) {
if (title.contains(i.toLowerCase())) {
evidenceModel.setClassifier4Passed(true);
evidenceFound = true;
}
}
//#E5 BODY: Is there any evidence of a hacking attack in the body text?
for (String i : keyWordList5) {
if (post.contains(i.toLowerCase())) {
evidenceModel.setClassifier5Passed(true);
evidenceFound = true;
}
}
//#E6 BODY: Are there any signs of usage of a security tool in the body text?
for (String i : keyWordList6) {
if (post.contains(i.toLowerCase())) {
evidenceModel.setClassifier6Passed(true);
evidenceFound = true;
}
}
//#E7 BODY: Are there any signs of security vulnerability in the body text?
for (String i : keyWordList7) {
if (post.contains(i.toLowerCase())) {
evidenceModel.setClassifier7Passed(true);
evidenceFound = true;
}
}
//#E8 BODY: Are there any signs of security vulnerability in the body text?
for (String i : keyWordList8) {
if (post.toLowerCase().contains(i.toLowerCase())) {
evidenceModel.setClassifier8Passed(true);
evidenceFound = true;
}
}
return evidenceFound;
}
private void buildClassifier() {
try{
loader.setDirectory(new File("/home/sewwandi/Documents/"));
dataRaw = loader.getDataSet();
filter = new StringToWordVector();
StopwordsHandler stopwordsHandler = new StopwordsHandler() {
Matcher matcher;
//@Override
public boolean isStopword(String s) {
if(stopWordList.contains(s) || s.length()<3 || s.matches(regex1) || s.matches(regex)) //matcher == p.matcher(s)
return true;
else return false;
}
};
filter.setStopwordsHandler(stopwordsHandler);
SnowballStemmer stemmer = new SnowballStemmer();
filter.setStemmer(stemmer);
filter.setLowerCaseTokens(true);
filter.setTFTransform(true);
filter.setIDFTransform(true);
filter.setInputFormat(dataRaw);
dataFiltered = Filter.useFilter(dataRaw, filter);
System.out.println("\n\nFiltered data:\n\n" + dataFiltered);
NaiveBayesMultinomial classifier = new NaiveBayesMultinomial();
classifier.buildClassifier(dataFiltered);
//System.out.println("\n\nClassifier model:\n\n" + classifier);
Evaluation evaluation = new Evaluation(dataFiltered);
evaluation.crossValidateModel(classifier,dataFiltered,10,new Random());
System.out.println(evaluation.toSummaryString()+evaluation.toMatrixString());
// generate curve
/* ThresholdCurve tc = new ThresholdCurve();
int classIndex = 0;
Instances result = tc.getCurve(evaluation.predictions(), classIndex);
// plot curve
ThresholdVisualizePanel vmc = new ThresholdVisualizePanel();
vmc.setROCString("(Area under ROC = " +
Utils.doubleToString(tc.getROCArea(result), 4) + ")");
vmc.setName(result.relationName());
PlotData2D tempd = new PlotData2D(result);
tempd.setPlotName(result.relationName());
tempd.addInstanceNumberAttribute();
// specify which points are connected
boolean[] cp = new boolean[result.numInstances()];
for (int n = 1; n < cp.length; n++)
cp[n] = true;
tempd.setConnectPoints(cp);
// add plot
vmc.addPlot(tempd);
// display curve
String plotName = vmc.getName();
final javax.swing.JFrame jf =
new javax.swing.JFrame("Weka Classifier Visualize: "+plotName);
jf.setSize(500,400);
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(vmc, BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
}
});
jf.setVisible(true);
*/
}
catch (IOException ex){
System.out.println("IOException");
}catch(Exception ex1){
}
}
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
outputFieldsDeclarer.declare(new Fields("post"));
// Following line is used to make Context and Evidence classifiers run parallel.
// outputFieldsDeclarer.declareStream("EvidenceClassifier-out", new Fields("post"));
}
}
| Evidence classifier dataset path added
| src/main/java/EvidenceClassifierBolt.java | Evidence classifier dataset path added | <ide><path>rc/main/java/EvidenceClassifierBolt.java
<ide>
<ide> private void buildClassifier() {
<ide> try{
<del> loader.setDirectory(new File("/home/sewwandi/Documents/"));
<add> loader.setDirectory(new File("~/IdeaProjects/LeakHawk/dataset/"));
<ide> dataRaw = loader.getDataSet();
<ide>
<ide> filter = new StringToWordVector(); |
|
Java | apache-2.0 | c53ba060fcb02288758fe2c4f284d6374017fc05 | 0 | opencb/opencga,j-coll/opencga,j-coll/opencga,j-coll/opencga,opencb/opencga,opencb/opencga,opencb/opencga,j-coll/opencga,opencb/opencga,opencb/opencga,j-coll/opencga,j-coll/opencga | /*
* Copyright 2015-2017 OpenCB
*
* 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.opencb.opencga.catalog.managers;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.opencb.biodata.models.variant.VariantFileMetadata;
import org.opencb.biodata.models.variant.stats.VariantSetStats;
import org.opencb.commons.datastore.core.ObjectMap;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.datastore.core.QueryResult;
import org.opencb.commons.datastore.core.result.Error;
import org.opencb.commons.datastore.core.result.FacetQueryResult;
import org.opencb.commons.datastore.core.result.WriteResult;
import org.opencb.commons.utils.CollectionUtils;
import org.opencb.commons.utils.FileUtils;
import org.opencb.opencga.catalog.audit.AuditManager;
import org.opencb.opencga.catalog.audit.AuditRecord;
import org.opencb.opencga.catalog.auth.authorization.AuthorizationManager;
import org.opencb.opencga.catalog.db.DBAdaptorFactory;
import org.opencb.opencga.catalog.db.api.*;
import org.opencb.opencga.catalog.db.mongodb.MongoDBAdaptorFactory;
import org.opencb.opencga.catalog.exceptions.CatalogDBException;
import org.opencb.opencga.catalog.exceptions.CatalogException;
import org.opencb.opencga.catalog.exceptions.CatalogIOException;
import org.opencb.opencga.catalog.exceptions.CatalogParameterException;
import org.opencb.opencga.catalog.io.CatalogIOManager;
import org.opencb.opencga.catalog.io.CatalogIOManagerFactory;
import org.opencb.opencga.catalog.monitor.daemons.IndexDaemon;
import org.opencb.opencga.catalog.stats.solr.CatalogSolrManager;
import org.opencb.opencga.catalog.utils.*;
import org.opencb.opencga.core.common.Entity;
import org.opencb.opencga.core.common.TimeUtils;
import org.opencb.opencga.core.common.UriUtils;
import org.opencb.opencga.core.config.Configuration;
import org.opencb.opencga.core.config.HookConfiguration;
import org.opencb.opencga.core.models.*;
import org.opencb.opencga.core.models.File;
import org.opencb.opencga.core.models.acls.permissions.FileAclEntry;
import org.opencb.opencga.core.models.acls.permissions.StudyAclEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.opencb.opencga.catalog.auth.authorization.CatalogAuthorizationManager.checkPermissions;
import static org.opencb.opencga.catalog.utils.FileMetadataReader.VARIANT_FILE_STATS;
import static org.opencb.opencga.core.common.JacksonUtils.getDefaultObjectMapper;
/**
* @author Jacobo Coll <[email protected]>
*/
public class FileManager extends AnnotationSetManager<File> {
private static final QueryOptions INCLUDE_STUDY_URI;
private static final QueryOptions INCLUDE_FILE_URI_PATH;
private static final Comparator<File> ROOT_FIRST_COMPARATOR;
private static final Comparator<File> ROOT_LAST_COMPARATOR;
protected static Logger logger;
private FileMetadataReader file;
private UserManager userManager;
public static final String SKIP_TRASH = "SKIP_TRASH";
public static final String DELETE_EXTERNAL_FILES = "DELETE_EXTERNAL_FILES";
public static final String FORCE_DELETE = "FORCE_DELETE";
public static final String GET_NON_DELETED_FILES = Status.READY + "," + File.FileStatus.TRASHED + "," + File.FileStatus.STAGE + ","
+ File.FileStatus.MISSING;
public static final String GET_NON_TRASHED_FILES = Status.READY + "," + File.FileStatus.STAGE + "," + File.FileStatus.MISSING;
private final String defaultFacet = "creationYear>>creationMonth;format;bioformat;format>>bioformat;status;"
+ "size[0..214748364800]:10737418240;numSamples[0..10]:1";
static {
INCLUDE_STUDY_URI = new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.URI.key());
INCLUDE_FILE_URI_PATH = new QueryOptions(QueryOptions.INCLUDE,
Arrays.asList(FileDBAdaptor.QueryParams.URI.key(), FileDBAdaptor.QueryParams.PATH.key(),
FileDBAdaptor.QueryParams.EXTERNAL.key()));
ROOT_FIRST_COMPARATOR = (f1, f2) -> (f1.getPath() == null ? 0 : f1.getPath().length())
- (f2.getPath() == null ? 0 : f2.getPath().length());
ROOT_LAST_COMPARATOR = (f1, f2) -> (f2.getPath() == null ? 0 : f2.getPath().length())
- (f1.getPath() == null ? 0 : f1.getPath().length());
logger = LoggerFactory.getLogger(FileManager.class);
}
FileManager(AuthorizationManager authorizationManager, AuditManager auditManager, CatalogManager catalogManager,
DBAdaptorFactory catalogDBAdaptorFactory, CatalogIOManagerFactory ioManagerFactory, Configuration configuration) {
super(authorizationManager, auditManager, catalogManager, catalogDBAdaptorFactory, ioManagerFactory, configuration);
file = new FileMetadataReader(this.catalogManager);
this.userManager = catalogManager.getUserManager();
}
public URI getUri(File file) throws CatalogException {
ParamUtils.checkObj(file, "File");
if (file.getUri() != null) {
return file.getUri();
} else {
QueryResult<File> fileQueryResult = fileDBAdaptor.get(file.getUid(), INCLUDE_STUDY_URI);
if (fileQueryResult.getNumResults() == 0) {
throw new CatalogException("File " + file.getUid() + " not found");
}
return fileQueryResult.first().getUri();
}
}
@Deprecated
public URI getUri(long studyId, String filePath) throws CatalogException {
ParamUtils.checkObj(filePath, "filePath");
List<File> parents = getParents(false, INCLUDE_FILE_URI_PATH, filePath, studyId).getResult();
for (File parent : parents) {
if (parent.getUri() != null) {
if (parent.isExternal()) {
throw new CatalogException("Cannot upload files to an external folder");
}
String relativePath = filePath.replaceFirst(parent.getPath(), "");
return Paths.get(parent.getUri()).resolve(relativePath).toUri();
}
}
URI studyUri = getStudyUri(studyId);
return filePath.isEmpty()
? studyUri
: catalogIOManagerFactory.get(studyUri).getFileUri(studyUri, filePath);
}
public Study getStudy(File file, String sessionId) throws CatalogException {
ParamUtils.checkObj(file, "file");
ParamUtils.checkObj(sessionId, "session id");
if (file.getStudyUid() <= 0) {
throw new CatalogException("Missing study uid field in file");
}
String user = catalogManager.getUserManager().getUserId(sessionId);
Query query = new Query(StudyDBAdaptor.QueryParams.UID.key(), file.getStudyUid());
QueryResult<Study> studyQueryResult = studyDBAdaptor.get(query, QueryOptions.empty(), user);
if (studyQueryResult.getNumResults() == 1) {
return studyQueryResult.first();
} else {
authorizationManager.checkCanViewStudy(file.getStudyUid(), user);
throw new CatalogException("Incorrect study uid");
}
}
public void matchUpVariantFiles(String studyStr, List<File> transformedFiles, String sessionId) throws CatalogException {
String userId = catalogManager.getUserManager().getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
for (File transformedFile : transformedFiles) {
authorizationManager.checkFilePermission(study.getUid(), transformedFile.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
String variantPathName = getOriginalFile(transformedFile.getPath());
if (variantPathName == null) {
// Skip the file.
logger.warn("The file {} is not a variant transformed file", transformedFile.getName());
continue;
}
// Search in the same path
logger.info("Looking for vcf file in path {}", variantPathName);
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), variantPathName)
.append(FileDBAdaptor.QueryParams.BIOFORMAT.key(), File.Bioformat.VARIANT);
List<File> fileList = fileDBAdaptor.get(query, new QueryOptions()).getResult();
if (fileList.isEmpty()) {
// Search by name in the whole study
String variantFileName = getOriginalFile(transformedFile.getName());
logger.info("Looking for vcf file by name {}", variantFileName);
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.NAME.key(), variantFileName)
.append(FileDBAdaptor.QueryParams.BIOFORMAT.key(), File.Bioformat.VARIANT);
fileList = new ArrayList<>(fileDBAdaptor.get(query, new QueryOptions()).getResult());
// In case of finding more than one file, try to find the proper one.
if (fileList.size() > 1) {
// Discard files already with a transformed file.
fileList.removeIf(file -> file.getIndex() != null
&& file.getIndex().getTransformedFile() != null
&& file.getIndex().getTransformedFile().getId() != transformedFile.getUid());
}
if (fileList.size() > 1) {
// Discard files not transformed or indexed.
fileList.removeIf(file -> file.getIndex() == null
|| file.getIndex().getStatus() == null
|| file.getIndex().getStatus().getName() == null
|| file.getIndex().getStatus().getName().equals(FileIndex.IndexStatus.NONE));
}
}
if (fileList.size() != 1) {
// VCF file not found
logger.warn("The vcf file corresponding to the file " + transformedFile.getName() + " could not be found");
continue;
}
File vcf = fileList.get(0);
// Look for the json file. It should be in the same directory where the transformed file is.
String jsonPathName = getMetaFile(transformedFile.getPath());
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), jsonPathName)
.append(FileDBAdaptor.QueryParams.FORMAT.key(), File.Format.JSON);
fileList = fileDBAdaptor.get(query, new QueryOptions()).getResult();
if (fileList.size() != 1) {
// Skip. This should not ever happen
logger.warn("The json file corresponding to the file " + transformedFile.getName() + " could not be found");
continue;
}
File json = fileList.get(0);
/* Update relations */
File.RelatedFile producedFromRelation = new File.RelatedFile(vcf.getUid(), File.RelatedFile.Relation.PRODUCED_FROM);
// Update json file
logger.debug("Updating json relation");
List<File.RelatedFile> relatedFiles = ParamUtils.defaultObject(json.getRelatedFiles(), ArrayList::new);
// Do not add twice the same relation
if (!relatedFiles.contains(producedFromRelation)) {
relatedFiles.add(producedFromRelation);
ObjectMap params = new ObjectMap(FileDBAdaptor.QueryParams.RELATED_FILES.key(), relatedFiles);
fileDBAdaptor.update(json.getUid(), params, QueryOptions.empty());
}
// Update transformed file
logger.debug("Updating transformed relation");
relatedFiles = ParamUtils.defaultObject(transformedFile.getRelatedFiles(), ArrayList::new);
// Do not add twice the same relation
if (!relatedFiles.contains(producedFromRelation)) {
relatedFiles.add(producedFromRelation);
transformedFile.setRelatedFiles(relatedFiles);
ObjectMap params = new ObjectMap(FileDBAdaptor.QueryParams.RELATED_FILES.key(), relatedFiles);
fileDBAdaptor.update(transformedFile.getUid(), params, QueryOptions.empty());
}
// Update vcf file
logger.debug("Updating vcf relation");
FileIndex index = vcf.getIndex();
if (index.getTransformedFile() == null) {
index.setTransformedFile(new FileIndex.TransformedFile(transformedFile.getUid(), json.getUid()));
}
String status = FileIndex.IndexStatus.NONE;
if (vcf.getIndex() != null && vcf.getIndex().getStatus() != null && vcf.getIndex().getStatus().getName() != null) {
status = vcf.getIndex().getStatus().getName();
}
if (FileIndex.IndexStatus.NONE.equals(status)) {
// If TRANSFORMED, TRANSFORMING, etc, do not modify the index status
index.setStatus(new FileIndex.IndexStatus(FileIndex.IndexStatus.TRANSFORMED, "Found transformed file"));
}
ObjectMap params = new ObjectMap(FileDBAdaptor.QueryParams.INDEX.key(), index);
fileDBAdaptor.update(vcf.getUid(), params, QueryOptions.empty());
// Update variant stats
Path statsFile = Paths.get(json.getUri().getRawPath());
try (InputStream is = FileUtils.newInputStream(statsFile)) {
VariantFileMetadata fileMetadata = getDefaultObjectMapper().readValue(is, VariantFileMetadata.class);
VariantSetStats stats = fileMetadata.getStats();
params = new ObjectMap(FileDBAdaptor.QueryParams.STATS.key(), new ObjectMap(VARIANT_FILE_STATS, stats));
update(studyStr, vcf.getPath(), params, new QueryOptions(), sessionId);
} catch (IOException e) {
throw new CatalogException("Error reading file \"" + statsFile + "\"", e);
}
}
}
public void setStatus(String studyStr, String fileId, String status, String message, String sessionId) throws CatalogException {
MyResource<File> resource = getUid(fileId, studyStr, sessionId);
String userId = resource.getUser();
long fileUid = resource.getResource().getUid();
authorizationManager.checkFilePermission(resource.getStudy().getUid(), fileUid, userId, FileAclEntry.FilePermissions.WRITE);
if (status != null && !File.FileStatus.isValid(status)) {
throw new CatalogException("The status " + status + " is not valid file status.");
}
ObjectMap parameters = new ObjectMap();
parameters.putIfNotNull(FileDBAdaptor.QueryParams.STATUS_NAME.key(), status);
parameters.putIfNotNull(FileDBAdaptor.QueryParams.STATUS_MSG.key(), message);
fileDBAdaptor.update(fileUid, parameters, QueryOptions.empty());
auditManager.recordUpdate(AuditRecord.Resource.file, fileUid, userId, parameters, null, null);
}
public QueryResult<FileIndex> updateFileIndexStatus(File file, String newStatus, String message, String sessionId)
throws CatalogException {
return updateFileIndexStatus(file, newStatus, message, null, sessionId);
}
public QueryResult<FileIndex> updateFileIndexStatus(File file, String newStatus, String message, Integer release, String sessionId)
throws CatalogException {
String userId = catalogManager.getUserManager().getUserId(sessionId);
Long studyId = file.getStudyUid();
authorizationManager.checkFilePermission(studyId, file.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
FileIndex index = file.getIndex();
if (index != null) {
if (!FileIndex.IndexStatus.isValid(newStatus)) {
throw new CatalogException("The status " + newStatus + " is not a valid status.");
} else {
index.setStatus(new FileIndex.IndexStatus(newStatus, message));
}
} else {
index = new FileIndex(userId, TimeUtils.getTime(), new FileIndex.IndexStatus(newStatus), -1, new ObjectMap());
}
if (release != null) {
if (newStatus.equals(FileIndex.IndexStatus.READY)) {
index.setRelease(release);
}
}
ObjectMap params = new ObjectMap(FileDBAdaptor.QueryParams.INDEX.key(), index);
fileDBAdaptor.update(file.getUid(), params, QueryOptions.empty());
auditManager.recordUpdate(AuditRecord.Resource.file, file.getUid(), userId, params, null, null);
return new QueryResult<>("Update file index", 0, 1, 1, "", "", Arrays.asList(index));
}
@Deprecated
public QueryResult<File> getParents(long fileId, QueryOptions options, String sessionId) throws CatalogException {
QueryResult<File> fileQueryResult = fileDBAdaptor.get(fileId, new QueryOptions(QueryOptions.INCLUDE,
Arrays.asList(FileDBAdaptor.QueryParams.PATH.key(), FileDBAdaptor.QueryParams.STUDY_UID.key())));
if (fileQueryResult.getNumResults() == 0) {
return fileQueryResult;
}
String userId = userManager.getUserId(sessionId);
authorizationManager.checkFilePermission(fileQueryResult.first().getStudyUid(), fileId, userId, FileAclEntry.FilePermissions.VIEW);
return getParents(true, options, fileQueryResult.first().getPath(), fileQueryResult.first().getStudyUid());
}
public QueryResult<File> createFolder(String studyStr, String path, File.FileStatus status, boolean parents, String description,
QueryOptions options, String sessionId) throws CatalogException {
ParamUtils.checkPath(path, "folderPath");
options = ParamUtils.defaultObject(options, QueryOptions::new);
String userId = catalogManager.getUserManager().getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
if (path.startsWith("/")) {
path = path.substring(1);
}
if (!path.endsWith("/")) {
path = path + "/";
}
QueryResult<File> fileQueryResult;
switch (checkPathExists(path, study.getUid())) {
case FREE_PATH:
fileQueryResult = create(studyStr, File.Type.DIRECTORY, File.Format.NONE, File.Bioformat.NONE, path, null,
description, status, 0, -1, null, -1, null, null, parents, null, options, sessionId);
break;
case DIRECTORY_EXISTS:
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), path);
fileQueryResult = fileDBAdaptor.get(query, options, userId);
fileQueryResult.setWarningMsg("Folder was already created");
break;
case FILE_EXISTS:
default:
throw new CatalogException("A file with the same name of the folder already exists in Catalog");
}
fileQueryResult.setId("Create folder");
return fileQueryResult;
}
public QueryResult<File> createFile(String studyStr, String path, String description, boolean parents, String content,
String sessionId) throws CatalogException {
ParamUtils.checkPath(path, "filePath");
String userId = catalogManager.getUserManager().getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
if (path.startsWith("/")) {
path = path.substring(1);
}
switch (checkPathExists(path, study.getUid())) {
case FREE_PATH:
return create(studyStr, File.Type.FILE, File.Format.PLAIN, File.Bioformat.UNKNOWN, path, null, description,
new File.FileStatus(File.FileStatus.READY), 0, -1, null, -1, null, null, parents, content, new QueryOptions(),
sessionId);
case FILE_EXISTS:
case DIRECTORY_EXISTS:
default:
throw new CatalogException("A file or folder with the same name already exists in the path of Catalog");
}
}
public QueryResult<File> create(String studyStr, File.Type type, File.Format format, File.Bioformat bioformat, String path,
String creationDate, String description, File.FileStatus status, long size, long experimentId,
List<Sample> samples, long jobId, Map<String, Object> stats, Map<String, Object> attributes,
boolean parents, String content, QueryOptions options, String sessionId)
throws CatalogException {
File file = new File(type, format, bioformat, path, description, status, size, samples, jobId, null, stats, attributes);
return create(studyStr, file, parents, content, options, sessionId);
}
@Override
public QueryResult<File> create(String studyStr, File entry, QueryOptions options, String sessionId) throws CatalogException {
throw new NotImplementedException("Call to create passing parents and content variables");
}
public QueryResult<File> create(String studyStr, File file, boolean parents, String content, QueryOptions options, String sessionId)
throws CatalogException {
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
return create(study, file, parents, content, options, sessionId);
}
public QueryResult<File> register(Study study, File file, boolean parents, QueryOptions options, String sessionId)
throws CatalogException {
String userId = userManager.getUserId(sessionId);
long studyId = study.getUid();
/** Check and set all the params and create a File object **/
ParamUtils.checkObj(file, "File");
ParamUtils.checkPath(file.getPath(), "path");
file.setType(ParamUtils.defaultObject(file.getType(), File.Type.FILE));
file.setFormat(ParamUtils.defaultObject(file.getFormat(), File.Format.PLAIN));
file.setBioformat(ParamUtils.defaultObject(file.getBioformat(), File.Bioformat.NONE));
file.setDescription(ParamUtils.defaultString(file.getDescription(), ""));
file.setRelatedFiles(ParamUtils.defaultObject(file.getRelatedFiles(), ArrayList::new));
file.setCreationDate(TimeUtils.getTime());
file.setModificationDate(file.getCreationDate());
if (file.getType() == File.Type.FILE) {
file.setStatus(ParamUtils.defaultObject(file.getStatus(), new File.FileStatus(File.FileStatus.STAGE)));
} else {
file.setStatus(ParamUtils.defaultObject(file.getStatus(), new File.FileStatus(File.FileStatus.READY)));
}
if (file.getSize() < 0) {
throw new CatalogException("Error: DiskUsage can't be negative!");
}
// if (file.getExperiment().getId() > 0 && !jobDBAdaptor.experimentExists(file.getExperiment().getId())) {
// throw new CatalogException("Experiment { id: " + file.getExperiment().getId() + "} does not exist.");
// }
file.setSamples(ParamUtils.defaultObject(file.getSamples(), ArrayList::new));
for (Sample sample : file.getSamples()) {
if (sample.getUid() <= 0 || !sampleDBAdaptor.exists(sample.getUid())) {
throw new CatalogException("Sample { id: " + sample.getUid() + "} does not exist.");
}
}
if (file.getJob() != null && file.getJob().getUid() > 0 && !jobDBAdaptor.exists(file.getJob().getUid())) {
throw new CatalogException("Job { id: " + file.getJob().getUid() + "} does not exist.");
}
file.setStats(ParamUtils.defaultObject(file.getStats(), HashMap::new));
file.setAttributes(ParamUtils.defaultObject(file.getAttributes(), HashMap::new));
if (file.getType() == File.Type.DIRECTORY && !file.getPath().endsWith("/")) {
file.setPath(file.getPath() + "/");
}
if (file.getType() == File.Type.FILE && file.getPath().endsWith("/")) {
file.setPath(file.getPath().substring(0, file.getPath().length() - 1));
}
file.setName(Paths.get(file.getPath()).getFileName().toString());
URI uri;
try {
if (file.getType() == File.Type.DIRECTORY) {
uri = getFileUri(studyId, file.getPath(), true);
} else {
uri = getFileUri(studyId, file.getPath(), false);
}
} catch (URISyntaxException e) {
throw new CatalogException(e);
}
file.setUri(uri);
// FIXME: Why am I doing this? Why am I not throwing an exception if it already exists?
// Check if it already exists
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), file.getPath())
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), "!=" + File.FileStatus.TRASHED + ";" + File.FileStatus.DELETED
+ ";" + File.FileStatus.DELETING + ";" + File.FileStatus.PENDING_DELETE + ";" + File.FileStatus.REMOVED);
if (fileDBAdaptor.count(query).first() > 0) {
logger.warn("The file {} already exists in catalog", file.getPath());
}
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.URI.key(), uri)
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), "!=" + File.FileStatus.TRASHED + ";" + File.FileStatus.DELETED
+ ";" + File.FileStatus.DELETING + ";" + File.FileStatus.PENDING_DELETE + ";" + File.FileStatus.REMOVED);
if (fileDBAdaptor.count(query).first() > 0) {
logger.warn("The uri {} of the file is already in catalog but on a different path", uri);
}
boolean external = isExternal(study, file.getPath(), uri);
file.setExternal(external);
file.setRelease(catalogManager.getStudyManager().getCurrentRelease(study, userId));
//Find parent. If parents == true, create folders.
String parentPath = getParentPath(file.getPath());
long parentFileId = fileDBAdaptor.getId(studyId, parentPath);
boolean newParent = false;
if (parentFileId < 0 && StringUtils.isNotEmpty(parentPath)) {
if (parents) {
newParent = true;
File parentFile = new File(File.Type.DIRECTORY, File.Format.NONE, File.Bioformat.NONE, parentPath, "",
new File.FileStatus(File.FileStatus.READY), 0, file.getSamples(), -1, null, Collections.emptyMap(),
Collections.emptyMap());
parentFileId = register(study, parentFile, parents, options, sessionId).first().getUid();
} else {
throw new CatalogDBException("Directory not found " + parentPath);
}
}
//Check permissions
if (parentFileId < 0) {
throw new CatalogException("Unable to create file without a parent file");
} else {
if (!newParent) {
//If parent has been created, for sure we have permissions to create the new file.
authorizationManager.checkFilePermission(studyId, parentFileId, userId, FileAclEntry.FilePermissions.WRITE);
}
}
List<VariableSet> variableSetList = validateNewAnnotationSetsAndExtractVariableSets(study.getUid(), file.getAnnotationSets());
file.setUuid(UUIDUtils.generateOpenCGAUUID(UUIDUtils.Entity.FILE));
checkHooks(file, study.getFqn(), HookConfiguration.Stage.CREATE);
QueryResult<File> queryResult = fileDBAdaptor.insert(studyId, file, variableSetList, options);
// We obtain the permissions set in the parent folder and set them to the file or folder being created
QueryResult<FileAclEntry> allFileAcls = authorizationManager.getAllFileAcls(studyId, parentFileId, userId, false);
// Propagate ACLs
if (allFileAcls.getNumResults() > 0) {
authorizationManager.replicateAcls(studyId, Arrays.asList(queryResult.first().getUid()), allFileAcls.getResult(), Entity.FILE);
}
auditManager.recordCreation(AuditRecord.Resource.file, queryResult.first().getUid(), userId, queryResult.first(), null, null);
matchUpVariantFiles(study.getFqn(), queryResult.getResult(), sessionId);
return queryResult;
}
private QueryResult<File> create(Study study, File file, boolean parents, String content, QueryOptions options, String sessionId)
throws CatalogException {
QueryResult<File> queryResult = register(study, file, parents, options, sessionId);
if (file.getType() == File.Type.FILE && StringUtils.isNotEmpty(content)) {
CatalogIOManager ioManager = catalogIOManagerFactory.getDefault();
// We set parents to true because the file has been successfully registered, which means the directories are already registered
// in catalog
ioManager.createDirectory(Paths.get(file.getUri()).getParent().toUri(), true);
InputStream inputStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
ioManager.createFile(file.getUri(), inputStream);
// Update file parameters
ObjectMap params = new ObjectMap()
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.READY)
.append(FileDBAdaptor.QueryParams.SIZE.key(), ioManager.getFileSize(file.getUri()));
queryResult = fileDBAdaptor.update(file.getUid(), params, QueryOptions.empty());
}
return queryResult;
}
/**
* Upload a file in Catalog.
*
* @param studyStr study where the file will be uploaded.
* @param fileInputStream Input stream of the file to be uploaded.
* @param file File object containing at least the basic metada necessary for a successful upload: path
* @param overwrite Overwrite the current file if any.
* @param parents boolean indicating whether unexisting parent folders should also be created automatically.
* @param sessionId session id of the user performing the upload.
* @return a QueryResult with the file uploaded.
* @throws CatalogException if the user does not have permissions or any other unexpected issue happens.
*/
public QueryResult<File> upload(String studyStr, InputStream fileInputStream, File file, boolean overwrite, boolean parents,
String sessionId) throws CatalogException {
// Check basic parameters
ParamUtils.checkObj(file, "file");
ParamUtils.checkParameter(file.getPath(), FileDBAdaptor.QueryParams.PATH.key());
if (StringUtils.isEmpty(file.getName())) {
file.setName(Paths.get(file.getPath()).toFile().getName());
}
ParamUtils.checkObj(fileInputStream, "file input stream");
QueryResult<Study> studyQueryResult = catalogManager.getStudyManager().get(studyStr,
new QueryOptions(QueryOptions.EXCLUDE, Arrays.asList(StudyDBAdaptor.QueryParams.VARIABLE_SET.key(),
StudyDBAdaptor.QueryParams.ATTRIBUTES.key())), sessionId);
if (studyQueryResult.getNumResults() == 0) {
throw new CatalogException("Study " + studyStr + " not found");
}
Study study = studyQueryResult.first();
QueryResult<File> parentFolders = getParents(false, QueryOptions.empty(), file.getPath(), study.getUid());
if (parentFolders.getNumResults() == 0) {
// There always must be at least the root folder
throw new CatalogException("Unexpected error happened.");
}
String userId = userManager.getUserId(sessionId);
// Check permissions over the most internal path
authorizationManager.checkFilePermission(study.getUid(), parentFolders.first().getUid(), userId,
FileAclEntry.FilePermissions.UPLOAD);
authorizationManager.checkFilePermission(study.getUid(), parentFolders.first().getUid(), userId,
FileAclEntry.FilePermissions.WRITE);
// We obtain the basic studyPath where we will upload the file temporarily
java.nio.file.Path studyPath = Paths.get(study.getUri());
java.nio.file.Path tempFilePath = studyPath.resolve("tmp_" + file.getName()).resolve(file.getName());
logger.info("Uploading file... Temporal file path: {}", tempFilePath.toString());
CatalogIOManager ioManager = catalogManager.getCatalogIOManagerFactory().getDefault();
// Create the temporal directory and upload the file
try {
if (!Files.exists(tempFilePath.getParent())) {
logger.debug("Creating temporal folder: {}", tempFilePath.getParent());
ioManager.createDirectory(tempFilePath.getParent().toUri(), true);
}
// Start uploading the file to the temporal directory
// Upload the file to a temporary folder
Files.copy(fileInputStream, tempFilePath);
} catch (Exception e) {
logger.error("Error uploading file {}", file.getName(), e);
// Clean temporal directory
ioManager.deleteDirectory(tempFilePath.getParent().toUri());
throw new CatalogException("Error uploading file " + file.getName(), e);
}
// Register the file in catalog
QueryResult<File> fileQueryResult;
try {
fileQueryResult = catalogManager.getFileManager().register(study, file, parents, QueryOptions.empty(), sessionId);
// Create the directories where the file will be placed (if they weren't created before)
ioManager.createDirectory(Paths.get(fileQueryResult.first().getUri()).getParent().toUri(), true);
new org.opencb.opencga.catalog.managers.FileUtils(catalogManager).upload(tempFilePath.toUri(), fileQueryResult.first(),
null, sessionId, false, overwrite, true, true, Long.MAX_VALUE);
File fileMetadata = new FileMetadataReader(catalogManager)
.setMetadataInformation(fileQueryResult.first(), null, null, sessionId, false);
fileQueryResult.setResult(Collections.singletonList(fileMetadata));
} catch (Exception e) {
logger.error("Error uploading file {}", file.getName(), e);
// Clean temporal directory
ioManager.deleteDirectory(tempFilePath.getParent().toUri());
throw new CatalogException("Error uploading file " + file.getName(), e);
}
// Clean temporal directory
ioManager.deleteDirectory(tempFilePath.getParent().toUri());
return fileQueryResult;
}
/*
* @deprecated This method if broken with multiple studies
*/
@Deprecated
public QueryResult<File> get(Long fileId, QueryOptions options, String sessionId) throws CatalogException {
return get(null, String.valueOf(fileId), options, sessionId);
}
@Override
public QueryResult<File> get(String studyStr, Query query, QueryOptions options, String sessionId) throws CatalogException {
query = ParamUtils.defaultObject(query, Query::new);
options = ParamUtils.defaultObject(options, QueryOptions::new);
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId, new QueryOptions(QueryOptions.INCLUDE,
StudyDBAdaptor.QueryParams.VARIABLE_SET.key()));
query.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
// Fix query if it contains any annotation
AnnotationUtils.fixQueryAnnotationSearch(study, query);
fixQueryObject(study, query, sessionId);
QueryResult<File> fileQueryResult = fileDBAdaptor.get(query, options, userId);
if (fileQueryResult.getNumResults() == 0 && query.containsKey(FileDBAdaptor.QueryParams.UID.key())) {
List<Long> idList = query.getAsLongList(FileDBAdaptor.QueryParams.UID.key());
for (Long myId : idList) {
authorizationManager.checkFilePermission(study.getUid(), myId, userId, FileAclEntry.FilePermissions.VIEW);
}
}
return fileQueryResult;
}
public QueryResult<FileTree> getTree(String fileIdStr, @Nullable String studyStr, Query query, QueryOptions queryOptions, int maxDepth,
String sessionId) throws CatalogException {
long startTime = System.currentTimeMillis();
queryOptions = ParamUtils.defaultObject(queryOptions, QueryOptions::new);
query = ParamUtils.defaultObject(query, Query::new);
if (queryOptions.containsKey(QueryOptions.INCLUDE)) {
// Add type to the queryOptions
List<String> asStringListOld = queryOptions.getAsStringList(QueryOptions.INCLUDE);
List<String> newList = new ArrayList<>(asStringListOld.size());
for (String include : asStringListOld) {
newList.add(include);
}
newList.add(FileDBAdaptor.QueryParams.TYPE.key());
queryOptions.put(QueryOptions.INCLUDE, newList);
} else {
// Avoid excluding type
if (queryOptions.containsKey(QueryOptions.EXCLUDE)) {
List<String> asStringListOld = queryOptions.getAsStringList(QueryOptions.EXCLUDE);
if (asStringListOld.contains(FileDBAdaptor.QueryParams.TYPE.key())) {
// Remove type from exclude options
if (asStringListOld.size() > 1) {
List<String> toExclude = new ArrayList<>(asStringListOld.size() - 1);
for (String s : asStringListOld) {
if (!s.equalsIgnoreCase(FileDBAdaptor.QueryParams.TYPE.key())) {
toExclude.add(s);
}
}
queryOptions.put(QueryOptions.EXCLUDE, StringUtils.join(toExclude.toArray(), ","));
} else {
queryOptions.remove(QueryOptions.EXCLUDE);
}
}
}
}
MyResource<File> resource = getUid(fileIdStr, studyStr, sessionId);
query.put(FileDBAdaptor.QueryParams.STUDY_UID.key(), resource.getStudy().getUid());
// Check if we can obtain the file from the dbAdaptor properly.
QueryOptions qOptions = new QueryOptions()
.append(QueryOptions.INCLUDE, Arrays.asList(FileDBAdaptor.QueryParams.PATH.key(), FileDBAdaptor.QueryParams.NAME.key(),
FileDBAdaptor.QueryParams.UID.key(), FileDBAdaptor.QueryParams.TYPE.key()));
QueryResult<File> fileQueryResult = fileDBAdaptor.get(resource.getResource().getUid(), qOptions);
if (fileQueryResult == null || fileQueryResult.getNumResults() != 1) {
throw new CatalogException("An error occurred with the database.");
}
// Check if the id does not correspond to a directory
if (!fileQueryResult.first().getType().equals(File.Type.DIRECTORY)) {
throw new CatalogException("The file introduced is not a directory.");
}
// Call recursive method
FileTree fileTree = getTree(fileQueryResult.first(), query, queryOptions, maxDepth, resource.getStudy().getUid(),
resource.getUser());
int dbTime = (int) (System.currentTimeMillis() - startTime);
int numResults = countFilesInTree(fileTree);
return new QueryResult<>("File tree", dbTime, numResults, numResults, "", "", Arrays.asList(fileTree));
}
public QueryResult<File> getFilesFromFolder(String folderStr, String studyStr, QueryOptions options, String sessionId)
throws CatalogException {
ParamUtils.checkObj(folderStr, "folder");
MyResource<File> resource = getUid(folderStr, studyStr, sessionId);
options = ParamUtils.defaultObject(options, QueryOptions::new);
if (!resource.getResource().getType().equals(File.Type.DIRECTORY)) {
throw new CatalogDBException("File {path:'" + resource.getResource().getPath() + "'} is not a folder.");
}
Query query = new Query(FileDBAdaptor.QueryParams.DIRECTORY.key(), resource.getResource().getPath());
return get(studyStr, query, options, sessionId);
}
@Override
public DBIterator<File> iterator(String studyStr, Query query, QueryOptions options, String sessionId) throws CatalogException {
query = ParamUtils.defaultObject(query, Query::new);
options = ParamUtils.defaultObject(options, QueryOptions::new);
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
fixQueryObject(study, query, sessionId);
query.put(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
return fileDBAdaptor.iterator(query, options, userId);
}
@Override
public QueryResult<File> search(String studyStr, Query query, QueryOptions options, String sessionId) throws CatalogException {
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId, new QueryOptions(QueryOptions.INCLUDE,
StudyDBAdaptor.QueryParams.VARIABLE_SET.key()));
// Fix query if it contains any annotation
AnnotationUtils.fixQueryAnnotationSearch(study, query);
fixQueryObject(study, query, sessionId);
query.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
QueryResult<File> queryResult = fileDBAdaptor.get(query, options, userId);
return queryResult;
}
void fixQueryObject(Study study, Query query, String sessionId) throws CatalogException {
// The samples introduced could be either ids or names. As so, we should use the smart resolutor to do this.
if (StringUtils.isNotEmpty(query.getString(FileDBAdaptor.QueryParams.SAMPLES.key()))) {
MyResources<Sample> resource = catalogManager.getSampleManager().getUids(
query.getAsStringList(FileDBAdaptor.QueryParams.SAMPLES.key()), study.getFqn(), sessionId);
query.put(FileDBAdaptor.QueryParams.SAMPLE_UIDS.key(), resource.getResourceList().stream().map(Sample::getUid)
.collect(Collectors.toList()));
query.remove(FileDBAdaptor.QueryParams.SAMPLES.key());
}
}
@Override
public QueryResult<File> count(String studyStr, Query query, String sessionId) throws CatalogException {
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId, new QueryOptions(QueryOptions.INCLUDE,
StudyDBAdaptor.QueryParams.VARIABLE_SET.key()));
// Fix query if it contains any annotation
AnnotationUtils.fixQueryAnnotationSearch(study, query);
// The samples introduced could be either ids or names. As so, we should use the smart resolutor to do this.
fixQueryObject(study, query, sessionId);
query.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
QueryResult<Long> queryResultAux = fileDBAdaptor.count(query, userId, StudyAclEntry.StudyPermissions.VIEW_FILES);
return new QueryResult<>("count", queryResultAux.getDbTime(), 0, queryResultAux.first(), queryResultAux.getWarningMsg(),
queryResultAux.getErrorMsg(), Collections.emptyList());
}
@Override
public WriteResult delete(String studyStr, Query query, ObjectMap params, String sessionId) {
Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new));
params = ParamUtils.defaultObject(params, ObjectMap::new);
WriteResult writeResult = new WriteResult("delete", -1, 0, 0, null, null, null);
String userId;
Study study;
StopWatch watch = StopWatch.createStarted();
// If the user is the owner or the admin, we won't check if he has permissions for every single entry
boolean checkPermissions;
// We try to get an iterator containing all the files to be deleted
DBIterator<File> fileIterator;
List<WriteResult.Fail> failedList = new ArrayList<>();
try {
userId = catalogManager.getUserManager().getUserId(sessionId);
study = catalogManager.getStudyManager().resolveId(studyStr, userId, new QueryOptions(QueryOptions.INCLUDE,
StudyDBAdaptor.QueryParams.VARIABLE_SET.key()));
// Fix query if it contains any annotation
AnnotationUtils.fixQueryAnnotationSearch(study, finalQuery);
fixQueryObject(study, finalQuery, sessionId);
finalQuery.append(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
// If the user is the owner or the admin, we won't check if he has permissions for every single entry
checkPermissions = !authorizationManager.checkIsOwnerOrAdmin(study.getUid(), userId);
fileIterator = fileDBAdaptor.iterator(finalQuery, QueryOptions.empty(), userId);
} catch (CatalogException e) {
logger.error("Delete file: {}", e.getMessage(), e);
writeResult.setError(new Error(-1, null, e.getMessage()));
writeResult.setDbTime((int) watch.getTime(TimeUnit.MILLISECONDS));
return writeResult;
}
// We need to avoid processing subfolders or subfiles of an already processed folder independently
Set<String> processedPaths = new HashSet<>();
boolean physicalDelete = params.getBoolean(SKIP_TRASH, false) || params.getBoolean(DELETE_EXTERNAL_FILES, false);
long numMatches = 0;
while (fileIterator.hasNext()) {
File file = fileIterator.next();
if (subpathInPath(file.getPath(), processedPaths)) {
// We skip this folder because it is a subfolder or subfile within an already processed folder
continue;
}
try {
if (checkPermissions) {
authorizationManager.checkFilePermission(study.getUid(), file.getUid(), userId, FileAclEntry.FilePermissions.DELETE);
}
// Check if the file can be deleted
List<File> fileList = checkCanDeleteFile(studyStr, file, physicalDelete, userId);
// Remove job references
MyResources<File> resourceIds = new MyResources<>(userId, study, fileList);
try {
removeJobReferences(resourceIds);
} catch (CatalogException e) {
logger.error("Could not remove job references: {}", e.getMessage(), e);
throw new CatalogException("Could not remove job references: " + e.getMessage(), e);
}
// Remove the index references in case it is a transformed file or folder
try {
updateIndexStatusAfterDeletionOfTransformedFile(study.getUid(), file);
} catch (CatalogException e) {
logger.error("Could not remove relation references: {}", e.getMessage(), e);
throw new CatalogException("Could not remove relation references: " + e.getMessage(), e);
}
if (file.isExternal()) {
// unlink
WriteResult result = unlink(study.getUid(), file);
writeResult.setNumModified(writeResult.getNumModified() + result.getNumModified());
writeResult.setNumMatches(writeResult.getNumMatches() + result.getNumMatches());
} else {
// local
if (physicalDelete) {
// physicalDelete
WriteResult result = physicalDelete(study.getUid(), file, params.getBoolean(FORCE_DELETE, false));
writeResult.setNumModified(writeResult.getNumModified() + result.getNumModified());
writeResult.setNumMatches(writeResult.getNumMatches() + result.getNumMatches());
failedList.addAll(result.getFailed());
} else {
// sendToTrash
WriteResult result = sendToTrash(study.getUid(), file);
writeResult.setNumModified(writeResult.getNumModified() + result.getNumModified());
writeResult.setNumMatches(writeResult.getNumMatches() + result.getNumMatches());
}
}
// We store the processed path as is
if (file.getType() == File.Type.DIRECTORY) {
processedPaths.add(file.getPath());
}
} catch (Exception e) {
numMatches += 1;
failedList.add(new WriteResult.Fail(file.getId(), e.getMessage()));
if (file.getType() == File.Type.FILE) {
logger.debug("Cannot delete file {}: {}", file.getId(), e.getMessage(), e);
} else {
logger.debug("Cannot delete folder {}: {}", file.getId(), e.getMessage(), e);
}
}
}
writeResult.setDbTime((int) watch.getTime(TimeUnit.MILLISECONDS));
writeResult.setFailed(failedList);
writeResult.setNumMatches(writeResult.getNumMatches() + numMatches);
if (!failedList.isEmpty()) {
writeResult.setWarning(Collections.singletonList(new Error(-1, null, "There are files that could not be deleted")));
}
return writeResult;
}
public QueryResult<File> unlink(@Nullable String studyStr, String fileIdStr, String sessionId) throws CatalogException, IOException {
ParamUtils.checkParameter(fileIdStr, "File");
MyResource<File> resource = catalogManager.getFileManager().getUid(fileIdStr, studyStr, sessionId);
String userId = resource.getUser();
long fileId = resource.getResource().getUid();
long studyUid = resource.getStudy().getUid();
// Check 2. User has the proper permissions to delete the file.
authorizationManager.checkFilePermission(studyUid, fileId, userId, FileAclEntry.FilePermissions.DELETE);
// // Check if we can obtain the file from the dbAdaptor properly.
// Query query = new Query()
// .append(FileDBAdaptor.QueryParams.UID.key(), fileId)
// .append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
// .append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), GET_NON_TRASHED_FILES);
// QueryResult<File> fileQueryResult = fileDBAdaptor.get(query, QueryOptions.empty());
// if (fileQueryResult == null || fileQueryResult.getNumResults() != 1) {
// throw new CatalogException("Cannot unlink file '" + fileIdStr + "'. The file was already deleted or unlinked.");
// }
//
// File file = fileQueryResult.first();
File file = resource.getResource();
// Check 3.
if (!file.isExternal()) {
throw new CatalogException("Only previously linked files can be unlinked. Please, use delete instead.");
}
// Check if the file can be deleted
List<File> fileList = checkCanDeleteFile(studyStr, file, false, userId);
// Remove job references
MyResources<File> fileResource = new MyResources<>(userId, resource.getStudy(), fileList);
try {
removeJobReferences(fileResource);
} catch (CatalogException e) {
logger.error("Could not remove job references: {}", e.getMessage(), e);
throw new CatalogException("Could not remove job references: " + e.getMessage(), e);
}
// Remove the index references in case it is a transformed file or folder
try {
updateIndexStatusAfterDeletionOfTransformedFile(studyUid, file);
} catch (CatalogException e) {
logger.error("Could not remove relation references: {}", e.getMessage(), e);
throw new CatalogException("Could not remove relation references: " + e.getMessage(), e);
}
unlink(studyUid, file);
Query query = new Query()
.append(FileDBAdaptor.QueryParams.UID.key(), fileId)
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyUid)
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), Constants.ALL_STATUS);
return fileDBAdaptor.get(query, new QueryOptions(), userId);
}
/**
* This method sets the status of the file to PENDING_DELETE in all cases and does never remove a file from the file system (performed
* by the daemon).
* However, it applies the following changes:
* - Status -> PENDING_DELETE
* - Path -> Renamed to {path}__DELETED_{time}
* - URI -> File or folder name from the file system renamed to {name}__DELETED_{time}
* URI in the database updated accordingly
*
* @param studyId study id.
* @param file file or folder.
* @return a WriteResult object.
*/
private WriteResult physicalDelete(long studyId, File file, boolean forceDelete) throws CatalogException {
StopWatch watch = StopWatch.createStarted();
String currentStatus = file.getStatus().getName();
if (File.FileStatus.DELETED.equals(currentStatus)) {
throw new CatalogException("The file was already deleted");
}
if (File.FileStatus.PENDING_DELETE.equals(currentStatus) && !forceDelete) {
throw new CatalogException("The file was already pending for deletion");
}
if (File.FileStatus.DELETING.equals(currentStatus)) {
throw new CatalogException("The file is already being deleted");
}
URI fileUri = getUri(file);
CatalogIOManager ioManager = catalogIOManagerFactory.get(fileUri);
// Set the path suffix to DELETED
String suffixName = INTERNAL_DELIMITER + File.FileStatus.DELETED + "_" + TimeUtils.getTime();
long numMatched = 0;
long numModified = 0;
List<WriteResult.Fail> failedList = new ArrayList<>();
if (file.getType() == File.Type.FILE) {
logger.debug("Deleting physical file {}" + file.getPath());
numMatched += 1;
try {
// 1. Set the file status to deleting
ObjectMap update = new ObjectMap()
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.DELETING)
.append(FileDBAdaptor.QueryParams.PATH.key(), file.getPath() + suffixName);
fileDBAdaptor.update(file.getUid(), update, QueryOptions.empty());
// 2. Delete the file from disk
try {
Files.delete(Paths.get(fileUri));
} catch (IOException e) {
logger.error("{}", e.getMessage(), e);
// We rollback and leave the file/folder in PENDING_DELETE status
update = new ObjectMap(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.PENDING_DELETE);
fileDBAdaptor.update(file.getUid(), update, QueryOptions.empty());
throw new CatalogException("Could not delete physical file/folder: " + e.getMessage(), e);
}
// 3. Update the file status in the database. Set to delete
update = new ObjectMap(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.DELETED);
fileDBAdaptor.update(file.getUid(), update, QueryOptions.empty());
numModified += 1;
} catch (CatalogException e) {
failedList.add(new WriteResult.Fail(file.getId(), e.getMessage()));
}
} else {
logger.debug("Starting physical deletion of folder {}", file.getId());
// Rename the directory in the filesystem.
URI newURI;
String basePath = Paths.get(file.getPath()).toString();
String suffixedPath;
if (!File.FileStatus.PENDING_DELETE.equals(currentStatus)) {
try {
newURI = UriUtils.createDirectoryUri(Paths.get(fileUri).toString() + suffixName);
} catch (URISyntaxException e) {
logger.error("URI exception: {}", e.getMessage(), e);
throw new CatalogException("URI exception: " + e.getMessage(), e);
}
logger.debug("Renaming {} to {}", fileUri.toString(), newURI.toString());
ioManager.rename(fileUri, newURI);
suffixedPath = basePath + suffixName;
} else {
// newURI is actually = to fileURI
newURI = fileUri;
// suffixedPath = basePath
suffixedPath = basePath;
}
// Obtain all files and folders within the folder
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + file.getPath() + "*")
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), GET_NON_DELETED_FILES);
logger.debug("Looking for files and folders inside {} to mark as {}", file.getPath(), forceDelete
? File.FileStatus.DELETED : File.FileStatus.PENDING_DELETE);
QueryOptions options = new QueryOptions();
if (forceDelete) {
options.append(QueryOptions.SORT, FileDBAdaptor.QueryParams.PATH.key())
.append(QueryOptions.ORDER, QueryOptions.DESCENDING);
}
DBIterator<File> iterator = fileDBAdaptor.iterator(query, options);
while (iterator.hasNext()) {
File auxFile = iterator.next();
numMatched += 1;
String newPath;
String newUri;
if (!File.FileStatus.PENDING_DELETE.equals(currentStatus)) {
// Edit the PATH
newPath = auxFile.getPath().replaceFirst(basePath, suffixedPath);
newUri = auxFile.getUri().toString().replaceFirst(fileUri.toString(), newURI.toString());
} else {
newPath = auxFile.getPath();
newUri = auxFile.getUri().toString();
}
try {
if (!forceDelete) {
// Deferred deletion
logger.debug("Replacing old uri {} for {}, old path {} for {}, and setting the status to {}",
auxFile.getUri().toString(), newUri, auxFile.getPath(), newPath, File.FileStatus.PENDING_DELETE);
ObjectMap updateParams = new ObjectMap()
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.PENDING_DELETE)
.append(FileDBAdaptor.QueryParams.URI.key(), newUri)
.append(FileDBAdaptor.QueryParams.PATH.key(), newPath);
fileDBAdaptor.update(auxFile.getUid(), updateParams, QueryOptions.empty());
} else {
// We delete the files and folders now
// 1. Set the file status to deleting
ObjectMap update = new ObjectMap()
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.DELETING)
.append(FileDBAdaptor.QueryParams.URI.key(), newUri)
.append(FileDBAdaptor.QueryParams.PATH.key(), newPath);
fileDBAdaptor.update(auxFile.getUid(), update, QueryOptions.empty());
// 2. Delete the file from disk
try {
Files.delete(Paths.get(newUri.replaceFirst("file://", "")));
} catch (IOException e) {
logger.error("{}", e.getMessage(), e);
// We rollback and leave the file/folder in PENDING_DELETE status
update = new ObjectMap(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.PENDING_DELETE);
fileDBAdaptor.update(auxFile.getUid(), update, QueryOptions.empty());
throw new CatalogException("Could not delete physical file/folder: " + e.getMessage(), e);
}
// 3. Update the file status in the database. Set to delete
update = new ObjectMap(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.DELETED);
fileDBAdaptor.update(auxFile.getUid(), update, QueryOptions.empty());
}
numModified += 1;
} catch (CatalogException e) {
failedList.add(new WriteResult.Fail(auxFile.getId(), e.getMessage()));
}
}
}
return new WriteResult("delete", (int) watch.getTime(TimeUnit.MILLISECONDS), numMatched, numModified, failedList, null, null);
}
private WriteResult sendToTrash(long studyId, File file) throws CatalogDBException {
// It doesn't really matter if file is a file or a directory. I can directly set the status of the file or the directory +
// subfiles and subdirectories doing a single query as I don't need to rename anything
// Obtain all files within the folder
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + file.getPath() + "*")
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), GET_NON_DELETED_FILES);
ObjectMap params = new ObjectMap()
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.TRASHED);
QueryResult<Long> update = fileDBAdaptor.update(query, params, QueryOptions.empty());
return new WriteResult("trash", update.getDbTime(), update.first(), update.first(), null, null, null);
}
private WriteResult unlink(long studyId, File file) throws CatalogDBException {
StopWatch watch = StopWatch.createStarted();
String suffixName = INTERNAL_DELIMITER + File.FileStatus.REMOVED + "_" + TimeUtils.getTime();
// Set the new path
String basePath = Paths.get(file.getPath()).toString();
String suffixedPath = basePath + suffixName;
long numMatched = 0;
long numModified = 0;
if (file.getType() == File.Type.FILE) {
numMatched += 1;
ObjectMap params = new ObjectMap()
.append(FileDBAdaptor.QueryParams.PATH.key(), file.getPath().replaceFirst(basePath, suffixedPath))
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.REMOVED);
logger.debug("Unlinking file {}", file.getPath());
fileDBAdaptor.update(file.getUid(), params, QueryOptions.empty());
numModified += 1;
} else {
// Obtain all files within the folder
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + file.getPath() + "*")
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), GET_NON_DELETED_FILES);
logger.debug("Looking for files and folders inside {} to unlink", file.getPath());
DBIterator<File> iterator = fileDBAdaptor.iterator(query, new QueryOptions());
while (iterator.hasNext()) {
File auxFile = iterator.next();
numMatched += 1;
ObjectMap updateParams = new ObjectMap()
.append(FileDBAdaptor.QueryParams.PATH.key(), auxFile.getPath().replaceFirst(basePath, suffixedPath))
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.REMOVED);
fileDBAdaptor.update(auxFile.getUid(), updateParams, QueryOptions.empty());
numModified += 1;
}
}
return new WriteResult("unlink", (int) watch.getTime(TimeUnit.MILLISECONDS), numMatched, numModified, null, null, null);
}
private boolean subpathInPath(String subpath, Set<String> pathSet) {
String[] split = StringUtils.split(subpath, "/");
String auxPath = "";
for (String s : split) {
auxPath += s + "/";
if (pathSet.contains(auxPath)) {
return true;
}
}
return false;
}
public QueryResult<File> updateAnnotations(String studyStr, String fileStr, String annotationSetId,
Map<String, Object> annotations, ParamUtils.CompleteUpdateAction action,
QueryOptions options, String token) throws CatalogException {
if (annotations == null || annotations.isEmpty()) {
return new QueryResult<>(fileStr, -1, -1, -1, "Nothing to do: The map of annotations is empty", "", Collections.emptyList());
}
ObjectMap params = new ObjectMap(AnnotationSetManager.ANNOTATIONS, new AnnotationSet(annotationSetId, "", annotations));
options = ParamUtils.defaultObject(options, QueryOptions::new);
options.put(Constants.ACTIONS, new ObjectMap(AnnotationSetManager.ANNOTATIONS, action));
return update(studyStr, fileStr, params, options, token);
}
public QueryResult<File> removeAnnotations(String studyStr, String fileStr, String annotationSetId,
List<String> annotations, QueryOptions options, String token) throws CatalogException {
return updateAnnotations(studyStr, fileStr, annotationSetId, new ObjectMap("remove", StringUtils.join(annotations, ",")),
ParamUtils.CompleteUpdateAction.REMOVE, options, token);
}
public QueryResult<File> resetAnnotations(String studyStr, String fileStr, String annotationSetId, List<String> annotations,
QueryOptions options, String token) throws CatalogException {
return updateAnnotations(studyStr, fileStr, annotationSetId, new ObjectMap("reset", StringUtils.join(annotations, ",")),
ParamUtils.CompleteUpdateAction.RESET, options, token);
}
@Override
public QueryResult<File> update(String studyStr, String entryStr, ObjectMap parameters, QueryOptions options, String sessionId)
throws CatalogException {
ParamUtils.checkObj(parameters, "Parameters");
options = ParamUtils.defaultObject(options, QueryOptions::new);
MyResource<File> resource = getUid(entryStr, studyStr, sessionId);
String userId = userManager.getUserId(sessionId);
File file = resource.getResource();
// Check permissions...
// Only check write annotation permissions if the user wants to update the annotation sets
if (parameters.containsKey(FileDBAdaptor.QueryParams.ANNOTATION_SETS.key())) {
authorizationManager.checkFilePermission(resource.getStudy().getUid(), resource.getResource().getUid(), resource.getUser(),
FileAclEntry.FilePermissions.WRITE_ANNOTATIONS);
}
// Only check update permissions if the user wants to update anything apart from the annotation sets
if ((parameters.size() == 1 && !parameters.containsKey(FileDBAdaptor.QueryParams.ANNOTATION_SETS.key()))
|| parameters.size() > 1) {
authorizationManager.checkFilePermission(resource.getStudy().getUid(), file.getUid(), userId,
FileAclEntry.FilePermissions.WRITE);
}
try {
ParamUtils.checkAllParametersExist(parameters.keySet().iterator(), (a) -> FileDBAdaptor.UpdateParams.getParam(a) != null);
} catch (CatalogParameterException e) {
throw new CatalogException("Could not update: " + e.getMessage(), e);
}
// We obtain the numeric ids of the samples given
if (StringUtils.isNotEmpty(parameters.getString(FileDBAdaptor.QueryParams.SAMPLES.key()))) {
List<String> sampleIdStr = parameters.getAsStringList(FileDBAdaptor.QueryParams.SAMPLES.key());
MyResources<Sample> sampleResource = catalogManager.getSampleManager().getUids(sampleIdStr, studyStr, sessionId);
// Avoid sample duplicates
Set<Long> sampleIdsSet = sampleResource.getResourceList().stream().map(Sample::getUid).collect(Collectors.toSet());
List<Sample> sampleList = new ArrayList<>(sampleIdsSet.size());
for (Long sampleId : sampleIdsSet) {
Sample sample = new Sample();
sample.setUid(sampleId);
sampleList.add(sample);
}
parameters.put(FileDBAdaptor.QueryParams.SAMPLES.key(), sampleList);
}
//Name must be changed with "rename".
if (parameters.containsKey(FileDBAdaptor.QueryParams.NAME.key())) {
logger.info("Rename file using update method!");
rename(studyStr, file.getPath(), parameters.getString(FileDBAdaptor.QueryParams.NAME.key()), sessionId);
}
return unsafeUpdate(resource.getStudy(), file, parameters, options, userId);
}
QueryResult<File> unsafeUpdate(Study study, File file, ObjectMap parameters, QueryOptions options, String userId)
throws CatalogException {
if (isRootFolder(file)) {
throw new CatalogException("Cannot modify root folder");
}
try {
ParamUtils.checkAllParametersExist(parameters.keySet().iterator(), (a) -> FileDBAdaptor.UpdateParams.getParam(a) != null);
} catch (CatalogParameterException e) {
throw new CatalogException("Could not update: " + e.getMessage(), e);
}
MyResource<File> resource = new MyResource<>(userId, study, file);
List<VariableSet> variableSetList = checkUpdateAnnotationsAndExtractVariableSets(resource, parameters, options, fileDBAdaptor);
String ownerId = studyDBAdaptor.getOwnerId(study.getUid());
fileDBAdaptor.update(file.getUid(), parameters, variableSetList, options);
QueryResult<File> queryResult = fileDBAdaptor.get(file.getUid(), options);
auditManager.recordUpdate(AuditRecord.Resource.file, file.getUid(), userId, parameters, null, null);
userDBAdaptor.updateUserLastModified(ownerId);
return queryResult;
}
private void removeJobReferences(MyResources<File> resource) throws CatalogException {
QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(
JobDBAdaptor.QueryParams.UID.key(), JobDBAdaptor.QueryParams.INPUT.key(), JobDBAdaptor.QueryParams.OUTPUT.key(),
JobDBAdaptor.QueryParams.OUT_DIR.key(), JobDBAdaptor.QueryParams.ATTRIBUTES.key()));
List<Long> resourceList = resource.getResourceList().stream().map(File::getUid).collect(Collectors.toList());
// Find all the jobs containing references to any of the files to be deleted
Query query = new Query()
.append(JobDBAdaptor.QueryParams.STUDY_UID.key(), resource.getStudy().getUid())
.append(JobDBAdaptor.QueryParams.INPUT_UID.key(), resourceList)
.append(JobDBAdaptor.QueryParams.STATUS_NAME.key(), Constants.ALL_STATUS);
QueryResult<Job> jobInputFiles = jobDBAdaptor.get(query, options);
query = new Query()
.append(JobDBAdaptor.QueryParams.STUDY_UID.key(), resource.getStudy().getUid())
.append(JobDBAdaptor.QueryParams.OUTPUT_UID.key(), resourceList)
.append(JobDBAdaptor.QueryParams.STATUS_NAME.key(), Constants.ALL_STATUS);
QueryResult<Job> jobOutputFiles = jobDBAdaptor.get(query, options);
query = new Query()
.append(JobDBAdaptor.QueryParams.STUDY_UID.key(), resource.getStudy().getUid())
.append(JobDBAdaptor.QueryParams.OUT_DIR_UID.key(), resourceList)
.append(JobDBAdaptor.QueryParams.STATUS_NAME.key(), Constants.ALL_STATUS);
QueryResult<Job> jobOutDirFolders = jobDBAdaptor.get(query, options);
// We create a job map that will contain all the changes done so far to avoid performing more queries
Map<Long, Job> jobMap = new HashMap<>();
Set<Long> fileIdsReferencedInJobs = new HashSet<>();
for (Job job : jobInputFiles.getResult()) {
fileIdsReferencedInJobs.addAll(job.getInput().stream().map(File::getUid).collect(Collectors.toList()));
jobMap.put(job.getUid(), job);
}
for (Job job : jobOutputFiles.getResult()) {
fileIdsReferencedInJobs.addAll(job.getOutput().stream().map(File::getUid).collect(Collectors.toList()));
jobMap.put(job.getUid(), job);
}
for (Job job : jobOutDirFolders.getResult()) {
fileIdsReferencedInJobs.add(job.getOutDir().getUid());
jobMap.put(job.getUid(), job);
}
if (fileIdsReferencedInJobs.isEmpty()) {
logger.info("No associated jobs found for the files to be deleted.");
return;
}
// We create a map with the files that are related to jobs that are going to be deleted
Map<Long, File> relatedFileMap = new HashMap<>();
for (Long fileId : resourceList) {
if (fileIdsReferencedInJobs.contains(fileId)) {
relatedFileMap.put(fileId, null);
}
}
if (relatedFileMap.isEmpty()) {
logger.error("Unexpected error: None of the matching jobs seem to be related to any of the files to be deleted");
throw new CatalogException("Internal error. Please, report to the OpenCGA administrators.");
}
// We obtain the current information of those files
query = new Query()
.append(FileDBAdaptor.QueryParams.UID.key(), relatedFileMap.keySet())
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), resource.getStudy().getUid())
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), GET_NON_DELETED_FILES);
QueryResult<File> fileQueryResult = fileDBAdaptor.get(query, QueryOptions.empty());
if (fileQueryResult.getNumResults() < relatedFileMap.size()) {
logger.error("Unexpected error: The number of files fetched does not match the number of files looked for.");
throw new CatalogException("Internal error. Please, report to the OpenCGA administrators.");
}
relatedFileMap = new HashMap<>();
for (File file : fileQueryResult.getResult()) {
relatedFileMap.put(file.getUid(), file);
}
// We update the input files from the jobs
for (Job jobAux : jobInputFiles.getResult()) {
Job job = jobMap.get(jobAux.getUid());
List<File> inputFiles = new ArrayList<>(job.getInput().size());
List<File> attributeFiles = new ArrayList<>(job.getInput().size());
for (File file : job.getInput()) {
if (relatedFileMap.containsKey(file.getUid())) {
attributeFiles.add(relatedFileMap.get(file.getUid()));
} else {
inputFiles.add(file);
}
}
if (attributeFiles.isEmpty()) {
logger.error("Unexpected error: Deleted file was apparently not found in the map of job associated files");
throw new CatalogException("Internal error. Please, report to the OpenCGA administrators.");
}
Map<String, Object> attributes = job.getAttributes();
ObjectMap opencgaAttributes;
if (!attributes.containsKey(Constants.PRIVATE_OPENCGA_ATTRIBUTES)) {
opencgaAttributes = new ObjectMap();
attributes.put(Constants.PRIVATE_OPENCGA_ATTRIBUTES, opencgaAttributes);
} else {
opencgaAttributes = (ObjectMap) attributes.get(Constants.PRIVATE_OPENCGA_ATTRIBUTES);
}
List<Object> fileList = opencgaAttributes.getAsList(Constants.JOB_DELETED_INPUT_FILES);
if (fileList == null || fileList.isEmpty()) {
fileList = new ArrayList<>(attributeFiles);
} else {
fileList = new ArrayList<>(fileList);
fileList.addAll(attributeFiles);
}
opencgaAttributes.put(Constants.JOB_DELETED_INPUT_FILES, fileList);
ObjectMap params = new ObjectMap()
.append(JobDBAdaptor.QueryParams.ATTRIBUTES.key(), attributes)
.append(JobDBAdaptor.QueryParams.INPUT.key(), inputFiles);
jobDBAdaptor.update(job.getUid(), params, QueryOptions.empty());
}
// We update the output files from the jobs
for (Job jobAux : jobOutputFiles.getResult()) {
Job job = jobMap.get(jobAux.getUid());
List<File> outputFiles = new ArrayList<>(job.getOutput().size());
List<File> attributeFiles = new ArrayList<>(job.getOutput().size());
for (File file : job.getOutput()) {
if (relatedFileMap.containsKey(file.getUid())) {
attributeFiles.add(relatedFileMap.get(file.getUid()));
} else {
outputFiles.add(file);
}
}
if (attributeFiles.isEmpty()) {
logger.error("Unexpected error: Deleted file was apparently not found in the map of job associated files");
throw new CatalogException("Internal error. Please, report to the OpenCGA administrators.");
}
Map<String, Object> attributes = job.getAttributes();
ObjectMap opencgaAttributes;
if (!attributes.containsKey(Constants.PRIVATE_OPENCGA_ATTRIBUTES)) {
opencgaAttributes = new ObjectMap();
attributes.put(Constants.PRIVATE_OPENCGA_ATTRIBUTES, opencgaAttributes);
} else {
opencgaAttributes = (ObjectMap) attributes.get(Constants.PRIVATE_OPENCGA_ATTRIBUTES);
}
List<Object> fileList = opencgaAttributes.getAsList(Constants.JOB_DELETED_OUTPUT_FILES);
if (fileList == null || fileList.isEmpty()) {
fileList = new ArrayList<>(attributeFiles);
} else {
fileList = new ArrayList<>(fileList);
fileList.addAll(attributeFiles);
}
opencgaAttributes.put(Constants.JOB_DELETED_OUTPUT_FILES, fileList);
ObjectMap params = new ObjectMap()
.append(JobDBAdaptor.QueryParams.ATTRIBUTES.key(), attributes)
.append(JobDBAdaptor.QueryParams.OUTPUT.key(), outputFiles);
jobDBAdaptor.update(job.getUid(), params, QueryOptions.empty());
}
// We update the outdir file from the jobs
for (Job jobAux : jobOutDirFolders.getResult()) {
Job job = jobMap.get(jobAux.getUid());
File outDir = job.getOutDir();
if (outDir == null || outDir.getUid() <= 0) {
logger.error("Unexpected error: Output directory from job not found?");
throw new CatalogException("Internal error. Please, report to the OpenCGA administrators.");
}
if (!relatedFileMap.containsKey(job.getOutDir().getUid())) {
logger.error("Unexpected error: Deleted output directory was apparently not found in the map of job associated files");
throw new CatalogException("Internal error. Please, report to the OpenCGA administrators.");
}
// We get the whole file entry
outDir = relatedFileMap.get(outDir.getUid());
Map<String, Object> attributes = job.getAttributes();
ObjectMap opencgaAttributes;
if (!attributes.containsKey(Constants.PRIVATE_OPENCGA_ATTRIBUTES)) {
opencgaAttributes = new ObjectMap();
attributes.put(Constants.PRIVATE_OPENCGA_ATTRIBUTES, opencgaAttributes);
} else {
opencgaAttributes = (ObjectMap) attributes.get(Constants.PRIVATE_OPENCGA_ATTRIBUTES);
}
opencgaAttributes.put(Constants.JOB_DELETED_OUTPUT_DIRECTORY, outDir);
ObjectMap params = new ObjectMap()
.append(JobDBAdaptor.QueryParams.ATTRIBUTES.key(), attributes)
.append(JobDBAdaptor.QueryParams.OUT_DIR.key(), -1L);
jobDBAdaptor.update(job.getUid(), params, QueryOptions.empty());
}
}
public QueryResult<File> link(String studyStr, URI uriOrigin, String pathDestiny, ObjectMap params, String sessionId)
throws CatalogException, IOException {
// We make two attempts to link to ensure the behaviour remains even if it is being called at the same time link from different
// threads
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
try {
return privateLink(study, uriOrigin, pathDestiny, params, sessionId);
} catch (CatalogException | IOException e) {
return privateLink(study, uriOrigin, pathDestiny, params, sessionId);
}
}
@Override
public QueryResult rank(String studyStr, Query query, String field, int numResults, boolean asc, String sessionId)
throws CatalogException {
query = ParamUtils.defaultObject(query, Query::new);
ParamUtils.checkObj(field, "field");
ParamUtils.checkObj(sessionId, "sessionId");
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
authorizationManager.checkStudyPermission(study.getUid(), userId, StudyAclEntry.StudyPermissions.VIEW_FILES);
// TODO: In next release, we will have to check the count parameter from the queryOptions object.
boolean count = true;
query.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
QueryResult queryResult = null;
if (count) {
// We do not need to check for permissions when we show the count of files
queryResult = fileDBAdaptor.rank(query, field, numResults, asc);
}
return ParamUtils.defaultObject(queryResult, QueryResult::new);
}
@Override
public QueryResult groupBy(@Nullable String studyStr, Query query, List<String> fields, QueryOptions options, String sessionId)
throws CatalogException {
query = ParamUtils.defaultObject(query, Query::new);
options = ParamUtils.defaultObject(options, QueryOptions::new);
if (fields == null || fields.size() == 0) {
throw new CatalogException("Empty fields parameter.");
}
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
fixQueryObject(study, query, sessionId);
// Add study id to the query
query.put(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
// We do not need to check for permissions when we show the count of files
QueryResult queryResult = fileDBAdaptor.groupBy(query, fields, options, userId);
return ParamUtils.defaultObject(queryResult, QueryResult::new);
}
public QueryResult<File> rename(String studyStr, String fileStr, String newName, String sessionId) throws CatalogException {
ParamUtils.checkFileName(newName, "name");
MyResource<File> resource = getUid(fileStr, studyStr, sessionId);
String userId = resource.getUser();
Study study = resource.getStudy();
String ownerId = StringUtils.split(study.getFqn(), "@")[0];
File file = resource.getResource();
authorizationManager.checkFilePermission(study.getUid(), file.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
if (file.getName().equals(newName)) {
return new QueryResult<>("rename", -1, 0, 0, "The file was already named " + newName, "", Collections.emptyList());
}
if (isRootFolder(file)) {
throw new CatalogException("Can not rename root folder");
}
String oldPath = file.getPath();
Path parent = Paths.get(oldPath).getParent();
String newPath;
if (parent == null) {
newPath = newName;
} else {
newPath = parent.resolve(newName).toString();
}
userDBAdaptor.updateUserLastModified(ownerId);
CatalogIOManager catalogIOManager;
URI oldUri = file.getUri();
URI newUri = Paths.get(oldUri).getParent().resolve(newName).toUri();
// URI studyUri = file.getUri();
boolean isExternal = file.isExternal(); //If the file URI is not null, the file is external located.
QueryResult<File> result;
switch (file.getType()) {
case DIRECTORY:
if (!isExternal) { //Only rename non external files
catalogIOManager = catalogIOManagerFactory.get(oldUri); // TODO? check if something in the subtree is not READY?
if (catalogIOManager.exists(oldUri)) {
catalogIOManager.rename(oldUri, newUri); // io.move() 1
}
}
result = fileDBAdaptor.rename(file.getUid(), newPath, newUri.toString(), null);
auditManager.recordUpdate(AuditRecord.Resource.file, file.getUid(), userId, new ObjectMap("path", newPath)
.append("name", newName), "rename", null);
break;
case FILE:
if (!isExternal) { //Only rename non external files
catalogIOManager = catalogIOManagerFactory.get(oldUri);
catalogIOManager.rename(oldUri, newUri);
}
result = fileDBAdaptor.rename(file.getUid(), newPath, newUri.toString(), null);
auditManager.recordUpdate(AuditRecord.Resource.file, file.getUid(), userId, new ObjectMap("path", newPath)
.append("name", newName), "rename", null);
break;
default:
throw new CatalogException("Unknown file type " + file.getType());
}
return result;
}
public DataInputStream grep(String studyStr, String fileStr, String pattern, QueryOptions options, String sessionId)
throws CatalogException {
MyResource<File> resource = getUid(fileStr, studyStr, sessionId);
authorizationManager.checkFilePermission(resource.getStudy().getUid(), resource.getResource().getUid(), resource.getUser(),
FileAclEntry.FilePermissions.VIEW);
URI fileUri = getUri(resource.getResource());
boolean ignoreCase = options.getBoolean("ignoreCase");
boolean multi = options.getBoolean("multi");
return catalogIOManagerFactory.get(fileUri).getGrepFileObject(fileUri, pattern, ignoreCase, multi);
}
public DataInputStream download(String studyStr, String fileStr, int start, int limit, QueryOptions options, String sessionId)
throws CatalogException {
MyResource<File> resource = getUid(fileStr, studyStr, sessionId);
authorizationManager.checkFilePermission(resource.getStudy().getUid(), resource.getResource().getUid(), resource.getUser(),
FileAclEntry.FilePermissions.DOWNLOAD);
URI fileUri = getUri(resource.getResource());
return catalogIOManagerFactory.get(fileUri).getFileObject(fileUri, start, limit);
}
public QueryResult<Job> index(String studyStr, List<String> fileList, String type, Map<String, String> params, String sessionId)
throws CatalogException {
params = ParamUtils.defaultObject(params, HashMap::new);
MyResources<File> resource = getUids(fileList, studyStr, sessionId);
List<File> fileFolderIdList = resource.getResourceList();
long studyId = resource.getStudy().getUid();
String userId = resource.getUser();
// Define the output directory where the indexes will be put
String outDirPath = ParamUtils.defaultString(params.get("outdir"), "/");
if (outDirPath != null && outDirPath.contains("/") && !outDirPath.endsWith("/")) {
outDirPath = outDirPath + "/";
}
File outDir;
try {
outDir = smartResolutor(resource.getStudy().getUid(), outDirPath, resource.getUser());
} catch (CatalogException e) {
logger.warn("'{}' does not exist. Trying to create the output directory.", outDirPath);
QueryResult<File> folder = createFolder(studyStr, outDirPath, new File.FileStatus(), true, "", new QueryOptions(), sessionId);
outDir = folder.first();
}
authorizationManager.checkFilePermission(studyId, outDir.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
QueryResult<Job> jobQueryResult;
List<File> fileIdList = new ArrayList<>();
String indexDaemonType = null;
String jobName = null;
String description = null;
QueryOptions queryOptions = new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(
FileDBAdaptor.QueryParams.NAME.key(),
FileDBAdaptor.QueryParams.PATH.key(),
FileDBAdaptor.QueryParams.URI.key(),
FileDBAdaptor.QueryParams.TYPE.key(),
FileDBAdaptor.QueryParams.BIOFORMAT.key(),
FileDBAdaptor.QueryParams.FORMAT.key(),
FileDBAdaptor.QueryParams.INDEX.key())
);
if (type.equals("VCF")) {
indexDaemonType = IndexDaemon.VARIANT_TYPE;
Boolean transform = Boolean.valueOf(params.get("transform"));
Boolean load = Boolean.valueOf(params.get("load"));
if (transform && !load) {
jobName = "variant_transform";
description = "Transform variants from " + fileList;
} else if (load && !transform) {
description = "Load variants from " + fileList;
jobName = "variant_load";
} else {
description = "Index variants from " + fileList;
jobName = "variant_index";
}
for (File file : fileFolderIdList) {
if (File.Type.DIRECTORY.equals(file.getType())) {
// Retrieve all the VCF files that can be found within the directory
String path = file.getPath().endsWith("/") ? file.getPath() : file.getPath() + "/";
Query query = new Query()
.append(FileDBAdaptor.QueryParams.FORMAT.key(), Arrays.asList(File.Format.VCF, File.Format.GVCF))
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + path + "*")
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId);
QueryResult<File> fileQueryResult = fileDBAdaptor.get(query, queryOptions);
if (fileQueryResult.getNumResults() == 0) {
throw new CatalogException("No VCF files could be found in directory " + file.getPath());
}
for (File fileTmp : fileQueryResult.getResult()) {
authorizationManager.checkFilePermission(studyId, fileTmp.getUid(), userId, FileAclEntry.FilePermissions.VIEW);
authorizationManager.checkFilePermission(studyId, fileTmp.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
fileIdList.add(fileTmp);
}
} else {
if (isTransformedFile(file.getName())) {
if (file.getRelatedFiles() == null || file.getRelatedFiles().isEmpty()) {
catalogManager.getFileManager().matchUpVariantFiles(studyStr, Collections.singletonList(file), sessionId);
}
if (file.getRelatedFiles() != null) {
for (File.RelatedFile relatedFile : file.getRelatedFiles()) {
if (File.RelatedFile.Relation.PRODUCED_FROM.equals(relatedFile.getRelation())) {
Query query = new Query(FileDBAdaptor.QueryParams.UID.key(), relatedFile.getFileId());
file = get(studyStr, query, null, sessionId).first();
break;
}
}
}
}
if (!File.Format.VCF.equals(file.getFormat()) && !File.Format.GVCF.equals(file.getFormat())) {
throw new CatalogException("The file " + file.getName() + " is not a VCF file.");
}
authorizationManager.checkFilePermission(studyId, file.getUid(), userId, FileAclEntry.FilePermissions.VIEW);
authorizationManager.checkFilePermission(studyId, file.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
fileIdList.add(file);
}
}
if (fileIdList.size() == 0) {
throw new CatalogException("Cannot send to index. No files could be found to be indexed.");
}
params.put("outdir", outDir.getId());
params.put("sid", sessionId);
} else if (type.equals("BAM")) {
indexDaemonType = IndexDaemon.ALIGNMENT_TYPE;
jobName = "AlignmentIndex";
for (File file : fileFolderIdList) {
if (File.Type.DIRECTORY.equals(file.getType())) {
// Retrieve all the BAM files that can be found within the directory
String path = file.getPath().endsWith("/") ? file.getPath() : file.getPath() + "/";
Query query = new Query(FileDBAdaptor.QueryParams.FORMAT.key(), Arrays.asList(File.Format.SAM, File.Format.BAM))
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + path + "*")
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId);
QueryResult<File> fileQueryResult = fileDBAdaptor.get(query, queryOptions);
if (fileQueryResult.getNumResults() == 0) {
throw new CatalogException("No SAM/BAM files could be found in directory " + file.getPath());
}
for (File fileTmp : fileQueryResult.getResult()) {
authorizationManager.checkFilePermission(studyId, fileTmp.getUid(), userId, FileAclEntry.FilePermissions.VIEW);
authorizationManager.checkFilePermission(studyId, fileTmp.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
fileIdList.add(fileTmp);
}
} else {
if (!File.Format.BAM.equals(file.getFormat()) && !File.Format.SAM.equals(file.getFormat())) {
throw new CatalogException("The file " + file.getName() + " is not a SAM/BAM file.");
}
authorizationManager.checkFilePermission(studyId, file.getUid(), userId, FileAclEntry.FilePermissions.VIEW);
authorizationManager.checkFilePermission(studyId, file.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
fileIdList.add(file);
}
}
}
if (fileIdList.size() == 0) {
throw new CatalogException("Cannot send to index. No files could be found to be indexed.");
}
String fileIds = fileIdList.stream().map(File::getId).collect(Collectors.joining(","));
params.put("file", fileIds);
List<File> outputList = outDir.getUid() > 0 ? Arrays.asList(outDir) : Collections.emptyList();
ObjectMap attributes = new ObjectMap();
attributes.put(IndexDaemon.INDEX_TYPE, indexDaemonType);
attributes.putIfNotNull(Job.OPENCGA_OUTPUT_DIR, outDirPath);
attributes.putIfNotNull(Job.OPENCGA_STUDY, resource.getStudy().getFqn());
logger.info("job description: " + description);
jobQueryResult = catalogManager.getJobManager().queue(studyStr, jobName, description, "opencga-analysis.sh",
Job.Type.INDEX, params, fileIdList, outputList, outDir, attributes, sessionId);
jobQueryResult.first().setToolId(jobName);
return jobQueryResult;
}
public void setFileIndex(String studyStr, String fileId, FileIndex index, String sessionId) throws CatalogException {
MyResource<File> resource = getUid(fileId, studyStr, sessionId);
authorizationManager.checkFilePermission(resource.getStudy().getUid(), resource.getResource().getUid(), resource.getUser(),
FileAclEntry.FilePermissions.WRITE);
ObjectMap parameters = new ObjectMap(FileDBAdaptor.QueryParams.INDEX.key(), index);
fileDBAdaptor.update(resource.getResource().getUid(), parameters, QueryOptions.empty());
auditManager.recordUpdate(AuditRecord.Resource.file, resource.getResource().getUid(), resource.getUser(), parameters, null, null);
}
public void setDiskUsage(String studyStr, String fileId, long size, String sessionId) throws CatalogException {
MyResource<File> resource = getUid(fileId, studyStr, sessionId);
authorizationManager.checkFilePermission(resource.getStudy().getUid(), resource.getResource().getUid(), resource.getUser(),
FileAclEntry.FilePermissions.WRITE);
ObjectMap parameters = new ObjectMap(FileDBAdaptor.QueryParams.SIZE.key(), size);
fileDBAdaptor.update(resource.getResource().getUid(), parameters, QueryOptions.empty());
auditManager.recordUpdate(AuditRecord.Resource.file, resource.getResource().getUid(), resource.getUser(), parameters, null, null);
}
@Deprecated
public void setModificationDate(String studyStr, String fileId, String date, String sessionId) throws CatalogException {
MyResource<File> resource = getUid(fileId, studyStr, sessionId);
String userId = resource.getUser();
long studyId = resource.getStudy().getUid();
authorizationManager.checkFilePermission(studyId, resource.getResource().getUid(), userId, FileAclEntry.FilePermissions.WRITE);
ObjectMap parameters = new ObjectMap(FileDBAdaptor.QueryParams.MODIFICATION_DATE.key(), date);
fileDBAdaptor.update(resource.getResource().getUid(), parameters, QueryOptions.empty());
auditManager.recordUpdate(AuditRecord.Resource.file, resource.getResource().getUid(), userId, parameters, null, null);
}
public void setUri(String studyStr, String fileId, String uri, String sessionId) throws CatalogException {
MyResource<File> resource = getUid(fileId, studyStr, sessionId);
String userId = resource.getUser();
long studyId = resource.getStudy().getUid();
authorizationManager.checkFilePermission(studyId, resource.getResource().getUid(), userId, FileAclEntry.FilePermissions.WRITE);
ObjectMap parameters = new ObjectMap(FileDBAdaptor.QueryParams.URI.key(), uri);
fileDBAdaptor.update(resource.getResource().getUid(), parameters, QueryOptions.empty());
auditManager.recordUpdate(AuditRecord.Resource.file, resource.getResource().getUid(), userId, parameters, null, null);
}
// ************************** ACLs ******************************** //
public List<QueryResult<FileAclEntry>> getAcls(String studyStr, List<String> fileList, String member, boolean silent, String sessionId)
throws CatalogException {
List<QueryResult<FileAclEntry>> fileAclList = new ArrayList<>(fileList.size());
for (String file : fileList) {
try {
MyResource<File> resource = getUid(file, studyStr, sessionId);
QueryResult<FileAclEntry> allFileAcls;
if (StringUtils.isNotEmpty(member)) {
allFileAcls = authorizationManager.getFileAcl(resource.getStudy().getUid(), resource.getResource().getUid(),
resource.getUser(), member);
} else {
allFileAcls = authorizationManager.getAllFileAcls(resource.getStudy().getUid(), resource.getResource().getUid(),
resource.getUser(), true);
}
allFileAcls.setId(file);
fileAclList.add(allFileAcls);
} catch (CatalogException e) {
if (silent) {
fileAclList.add(new QueryResult<>(file, 0, 0, 0, "", e.toString(), new ArrayList<>(0)));
} else {
throw e;
}
}
}
return fileAclList;
}
public List<QueryResult<FileAclEntry>> updateAcl(String studyStr, List<String> fileList, String memberIds,
File.FileAclParams fileAclParams, String sessionId) throws CatalogException {
int count = 0;
count += fileList != null && !fileList.isEmpty() ? 1 : 0;
count += StringUtils.isNotEmpty(fileAclParams.getSample()) ? 1 : 0;
if (count > 1) {
throw new CatalogException("Update ACL: Only one of these parameters are allowed: file or sample per query.");
} else if (count == 0) {
throw new CatalogException("Update ACL: At least one of these parameters should be provided: file or sample");
}
if (fileAclParams.getAction() == null) {
throw new CatalogException("Invalid action found. Please choose a valid action to be performed.");
}
List<String> permissions = Collections.emptyList();
if (StringUtils.isNotEmpty(fileAclParams.getPermissions())) {
permissions = Arrays.asList(fileAclParams.getPermissions().trim().replaceAll("\\s", "").split(","));
checkPermissions(permissions, FileAclEntry.FilePermissions::valueOf);
}
if (StringUtils.isNotEmpty(fileAclParams.getSample())) {
// Obtain the sample ids
MyResources<Sample> resource = catalogManager.getSampleManager().getUids(
Arrays.asList(StringUtils.split(fileAclParams.getSample(), ",")), studyStr, sessionId);
Query query = new Query(FileDBAdaptor.QueryParams.SAMPLE_UIDS.key(), resource.getResourceList().stream().map(Sample::getUid)
.collect(Collectors.toList()));
QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, FileDBAdaptor.QueryParams.UID.key());
QueryResult<File> fileQueryResult = catalogManager.getFileManager().get(studyStr, query, options, sessionId);
fileList = fileQueryResult.getResult().stream().map(File::getUid).map(String::valueOf).collect(Collectors.toList());
}
// Obtain the resource ids
MyResources<File> resource = getUids(fileList, studyStr, sessionId);
authorizationManager.checkCanAssignOrSeePermissions(resource.getStudy().getUid(), resource.getUser());
// Increase the list with the files/folders within the list of ids that correspond with folders
resource = getRecursiveFilesAndFolders(resource);
// Validate that the members are actually valid members
List<String> members;
if (memberIds != null && !memberIds.isEmpty()) {
members = Arrays.asList(memberIds.split(","));
} else {
members = Collections.emptyList();
}
authorizationManager.checkNotAssigningPermissionsToAdminsGroup(members);
checkMembers(resource.getStudy().getUid(), members);
// catalogManager.getStudyManager().membersHavePermissionsInStudy(resourceIds.getStudyId(), members);
switch (fileAclParams.getAction()) {
case SET:
// Todo: Remove this in 1.4
List<String> allFilePermissions = EnumSet.allOf(FileAclEntry.FilePermissions.class)
.stream()
.map(String::valueOf)
.collect(Collectors.toList());
return authorizationManager.setAcls(resource.getStudy().getUid(), resource.getResourceList().stream().map(File::getUid)
.collect(Collectors.toList()), members, permissions, allFilePermissions, Entity.FILE);
case ADD:
return authorizationManager.addAcls(resource.getStudy().getUid(), resource.getResourceList().stream().map(File::getUid)
.collect(Collectors.toList()), members, permissions, Entity.FILE);
case REMOVE:
return authorizationManager.removeAcls(resource.getResourceList().stream().map(File::getUid).collect(Collectors.toList()),
members, permissions, Entity.FILE);
case RESET:
return authorizationManager.removeAcls(resource.getResourceList().stream().map(File::getUid).collect(Collectors.toList()),
members, null, Entity.FILE);
default:
throw new CatalogException("Unexpected error occurred. No valid action found.");
}
}
// ************************** Private methods ******************************** //
private boolean isRootFolder(File file) throws CatalogException {
ParamUtils.checkObj(file, "File");
return file.getPath().isEmpty();
}
/**
* Fetch all the recursive files and folders within the list of file ids given.
*
* @param resource ResourceId object containing the list of file ids, studyId and userId.
* @return a new ResourceId object
*/
private MyResources<File> getRecursiveFilesAndFolders(MyResources<File> resource) throws CatalogException {
List<File> fileList = new LinkedList<>();
fileList.addAll(resource.getResourceList());
Set<Long> uidFileSet = new HashSet<>();
uidFileSet.addAll(resource.getResourceList().stream().map(File::getUid).collect(Collectors.toSet()));
List<String> pathList = new ArrayList<>();
for (File file : resource.getResourceList()) {
if (file.getType().equals(File.Type.DIRECTORY)) {
pathList.add("~^" + file.getPath());
}
}
QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, FileDBAdaptor.QueryParams.UID.key());
if (CollectionUtils.isNotEmpty(pathList)) {
// Search for all the files within the list of paths
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), resource.getStudy().getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), pathList);
QueryResult<File> fileQueryResult1 = fileDBAdaptor.get(query, options);
for (File file1 : fileQueryResult1.getResult()) {
if (!uidFileSet.contains(file1.getUid())) {
uidFileSet.add(file1.getUid());
fileList.add(file1);
}
}
}
return new MyResources<>(resource.getUser(), resource.getStudy(), fileList);
}
private List<String> getParentPaths(String filePath) {
String path = "";
String[] split = filePath.split("/");
List<String> paths = new ArrayList<>(split.length + 1);
paths.add(""); //Add study root folder
//Add intermediate folders
//Do not add the last split, could be a file or a folder..
//Depending on this, it could end with '/' or not.
for (int i = 0; i < split.length - 1; i++) {
String f = split[i];
path = path + f + "/";
paths.add(path);
}
paths.add(filePath); //Add the file path
return paths;
}
@Override
File smartResolutor(long studyUid, String fileName, String user) throws CatalogException {
if (UUIDUtils.isOpenCGAUUID(fileName)) {
// We search as uuid
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyUid)
.append(FileDBAdaptor.QueryParams.UUID.key(), fileName);
QueryResult<File> pathQueryResult = fileDBAdaptor.get(query, QueryOptions.empty());
if (pathQueryResult.getNumResults() > 1) {
throw new CatalogException("Error: More than one file id found based on " + fileName);
} else if (pathQueryResult.getNumResults() == 1) {
return pathQueryResult.first();
}
}
fileName = fileName.replace(":", "/");
if (fileName.startsWith("/")) {
fileName = fileName.substring(1);
}
// We search as a path
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyUid)
.append(FileDBAdaptor.QueryParams.PATH.key(), fileName);
QueryResult<File> pathQueryResult = fileDBAdaptor.get(query, QueryOptions.empty());
if (pathQueryResult.getNumResults() > 1) {
throw new CatalogException("Error: More than one file id found based on " + fileName);
} else if (pathQueryResult.getNumResults() == 1) {
return pathQueryResult.first();
}
if (!fileName.contains("/")) {
// We search as a fileName as well
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyUid)
.append(FileDBAdaptor.QueryParams.NAME.key(), fileName);
QueryResult<File> nameQueryResult = fileDBAdaptor.get(query, QueryOptions.empty());
if (nameQueryResult.getNumResults() > 1) {
throw new CatalogException("Error: More than one file id found based on " + fileName);
} else if (nameQueryResult.getNumResults() == 1) {
return nameQueryResult.first();
}
}
throw new CatalogException("File " + fileName + " not found");
}
//FIXME: This should use org.opencb.opencga.storage.core.variant.io.VariantReaderUtils
private String getOriginalFile(String name) {
if (name.endsWith(".variants.avro.gz")
|| name.endsWith(".variants.proto.gz")
|| name.endsWith(".variants.json.gz")) {
int idx = name.lastIndexOf(".variants.");
return name.substring(0, idx);
} else {
return null;
}
}
private boolean isTransformedFile(String name) {
return getOriginalFile(name) != null;
}
private String getMetaFile(String path) {
String file = getOriginalFile(path);
if (file != null) {
return file + ".file.json.gz";
} else {
return null;
}
}
private QueryResult<File> getParents(boolean rootFirst, QueryOptions options, String filePath, long studyId) throws CatalogException {
List<String> paths = getParentPaths(filePath);
Query query = new Query(FileDBAdaptor.QueryParams.PATH.key(), paths);
query.put(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId);
QueryResult<File> result = fileDBAdaptor.get(query, options);
result.getResult().sort(rootFirst ? ROOT_FIRST_COMPARATOR : ROOT_LAST_COMPARATOR);
return result;
}
private String getParentPath(String path) {
Path parent = Paths.get(path).getParent();
String parentPath;
if (parent == null) { //If parent == null, the file is in the root of the study
parentPath = "";
} else {
parentPath = parent.toString() + "/";
}
return parentPath;
}
/**
* Get the URI where a file should be in Catalog, given a study and a path.
*
* @param studyId Study identifier
* @param path Path to locate
* @param directory Boolean indicating if the file is a directory
* @return URI where the file should be placed
* @throws CatalogException CatalogException
*/
private URI getFileUri(long studyId, String path, boolean directory) throws CatalogException, URISyntaxException {
// Get the closest existing parent. If parents == true, may happen that the parent is not registered in catalog yet.
File existingParent = getParents(false, null, path, studyId).first();
//Relative path to the existing parent
String relativePath = Paths.get(existingParent.getPath()).relativize(Paths.get(path)).toString();
if (path.endsWith("/") && !relativePath.endsWith("/")) {
relativePath += "/";
}
String uriStr = Paths.get(existingParent.getUri().getPath()).resolve(relativePath).toString();
if (directory) {
return UriUtils.createDirectoryUri(uriStr);
} else {
return UriUtils.createUri(uriStr);
}
}
private boolean isExternal(Study study, String catalogFilePath, URI fileUri) throws CatalogException {
URI studyUri = study.getUri();
String studyFilePath = studyUri.resolve(catalogFilePath).getPath();
String originalFilePath = fileUri.getPath();
logger.info("Study file path: {}", studyFilePath);
logger.info("File path: {}", originalFilePath);
return !studyFilePath.equals(originalFilePath);
}
private FileTree getTree(File folder, Query query, QueryOptions queryOptions, int maxDepth, long studyId, String userId)
throws CatalogDBException {
if (maxDepth == 0) {
return null;
}
try {
authorizationManager.checkFilePermission(studyId, folder.getUid(), userId, FileAclEntry.FilePermissions.VIEW);
} catch (CatalogException e) {
return null;
}
// Update the new path to be looked for
query.put(FileDBAdaptor.QueryParams.DIRECTORY.key(), folder.getPath());
FileTree fileTree = new FileTree(folder);
List<FileTree> children = new ArrayList<>();
// Obtain the files and directories inside the directory
QueryResult<File> fileQueryResult = fileDBAdaptor.get(query, queryOptions);
for (File fileAux : fileQueryResult.getResult()) {
if (fileAux.getType().equals(File.Type.DIRECTORY)) {
FileTree subTree = getTree(fileAux, query, queryOptions, maxDepth - 1, studyId, userId);
if (subTree != null) {
children.add(subTree);
}
} else {
try {
authorizationManager.checkFilePermission(studyId, fileAux.getUid(), userId, FileAclEntry.FilePermissions.VIEW);
children.add(new FileTree(fileAux));
} catch (CatalogException e) {
continue;
}
}
}
fileTree.setChildren(children);
return fileTree;
}
private int countFilesInTree(FileTree fileTree) {
int count = 1;
for (FileTree tree : fileTree.getChildren()) {
count += countFilesInTree(tree);
}
return count;
}
/**
* Method to check if a files matching a query can be deleted. It will only be possible to delete files as long as they are not indexed.
*
* @param query Query object.
* @param physicalDelete boolean indicating whether the files matching the query should be completely deleted from the file system or
* they should be sent to the trash bin.
* @param studyId Study where the query will be applied.
* @param userId user for which DELETE permissions will be checked.
* @return the list of files scanned that can be deleted.
* @throws CatalogException if any of the files cannot be deleted.
*/
public List<File> checkCanDeleteFiles(Query query, boolean physicalDelete, long studyId, String userId) throws CatalogException {
String statusQuery = physicalDelete ? GET_NON_DELETED_FILES : GET_NON_TRASHED_FILES;
QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(FileDBAdaptor.QueryParams.UID.key(),
FileDBAdaptor.QueryParams.NAME.key(), FileDBAdaptor.QueryParams.TYPE.key(), FileDBAdaptor.QueryParams.RELATED_FILES.key(),
FileDBAdaptor.QueryParams.SIZE.key(), FileDBAdaptor.QueryParams.URI.key(), FileDBAdaptor.QueryParams.PATH.key(),
FileDBAdaptor.QueryParams.INDEX.key(), FileDBAdaptor.QueryParams.STATUS.key(), FileDBAdaptor.QueryParams.EXTERNAL.key()));
Query myQuery = new Query(query);
myQuery.put(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId);
myQuery.put(FileDBAdaptor.QueryParams.STATUS_NAME.key(), statusQuery);
QueryResult<File> fileQueryResult = fileDBAdaptor.get(myQuery, options);
return checkCanDeleteFiles(fileQueryResult.getResult().iterator(), physicalDelete, String.valueOf(studyId), userId);
}
public List<File> checkCanDeleteFiles(Iterator<File> fileIterator, boolean physicalDelete, String studyStr, String userId)
throws CatalogException {
List<File> filesChecked = new LinkedList<>();
while (fileIterator.hasNext()) {
filesChecked.addAll(checkCanDeleteFile(studyStr, fileIterator.next(), physicalDelete, userId));
}
return filesChecked;
}
public List<File> checkCanDeleteFile(String studyStr, File file, boolean physicalDelete, String userId) throws CatalogException {
String statusQuery = physicalDelete ? GET_NON_DELETED_FILES : GET_NON_TRASHED_FILES;
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(FileDBAdaptor.QueryParams.UID.key(),
FileDBAdaptor.QueryParams.NAME.key(), FileDBAdaptor.QueryParams.TYPE.key(), FileDBAdaptor.QueryParams.RELATED_FILES.key(),
FileDBAdaptor.QueryParams.SIZE.key(), FileDBAdaptor.QueryParams.URI.key(), FileDBAdaptor.QueryParams.PATH.key(),
FileDBAdaptor.QueryParams.INDEX.key(), FileDBAdaptor.QueryParams.STATUS.key(), FileDBAdaptor.QueryParams.EXTERNAL.key()));
List<File> filesToAnalyse = new LinkedList<>();
if (file.getType() == File.Type.FILE) {
filesToAnalyse.add(file);
} else {
// We cannot delete the root folder
if (isRootFolder(file)) {
throw new CatalogException("Root directories cannot be deleted");
}
// Get all recursive files and folders
Query newQuery = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + file.getPath() + "*")
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), statusQuery);
QueryResult<File> recursiveFileQueryResult = fileDBAdaptor.get(newQuery, options);
if (file.isExternal()) {
// Check there aren't local files within the directory
List<String> wrongFiles = new LinkedList<>();
for (File nestedFile : recursiveFileQueryResult.getResult()) {
if (!nestedFile.isExternal()) {
wrongFiles.add(nestedFile.getPath());
}
}
if (!wrongFiles.isEmpty()) {
throw new CatalogException("Local files {" + StringUtils.join(wrongFiles, ", ") + "} detected within the external "
+ "folder " + file.getPath() + ". Please, delete those folders or files manually first");
}
} else {
// Check there aren't external files within the directory
List<String> wrongFiles = new LinkedList<>();
for (File nestedFile : recursiveFileQueryResult.getResult()) {
if (nestedFile.isExternal()) {
wrongFiles.add(nestedFile.getPath());
}
}
if (!wrongFiles.isEmpty()) {
throw new CatalogException("External files {" + StringUtils.join(wrongFiles, ", ") + "} detected within the local "
+ "folder " + file.getPath() + ". Please, unlink those folders or files manually first");
}
}
filesToAnalyse.addAll(recursiveFileQueryResult.getResult());
}
// If the user is the owner or the admin, we won't check if he has permissions for every single file
boolean checkPermissions = !authorizationManager.checkIsOwnerOrAdmin(study.getUid(), userId);
Set<Long> transformedFromFileIds = new HashSet<>();
for (File fileAux : filesToAnalyse) {
if (checkPermissions) {
authorizationManager.checkFilePermission(study.getUid(), fileAux.getUid(), userId, FileAclEntry.FilePermissions.DELETE);
}
// Check the file status is not STAGE or MISSING
if (fileAux.getStatus() == null) {
throw new CatalogException("Cannot check file status for deletion");
}
if (File.FileStatus.STAGE.equals(fileAux.getStatus().getName())
|| File.FileStatus.MISSING.equals(fileAux.getStatus().getName())) {
throw new CatalogException("Cannot delete file: " + fileAux.getName() + ". The status is " + fileAux.getStatus().getName());
}
// Check the index status
if (fileAux.getIndex() != null && fileAux.getIndex().getStatus() != null
&& !FileIndex.IndexStatus.NONE.equals(fileAux.getIndex().getStatus().getName())
&& !FileIndex.IndexStatus.TRANSFORMED.equals(fileAux.getIndex().getStatus().getName())) {
throw new CatalogException("Cannot delete file: " + fileAux.getName() + ". The index status is "
+ fileAux.getIndex().getStatus().getName());
}
// Check if the file is produced from other file being indexed and add them to the transformedFromFileIds set
if (fileAux.getRelatedFiles() != null && !fileAux.getRelatedFiles().isEmpty()) {
transformedFromFileIds.addAll(
fileAux.getRelatedFiles().stream()
.filter(myFile -> myFile.getRelation() == File.RelatedFile.Relation.PRODUCED_FROM)
.map(File.RelatedFile::getFileId)
.collect(Collectors.toSet())
);
}
}
// Check the original files are not being indexed at the moment
if (!transformedFromFileIds.isEmpty()) {
Query query = new Query(FileDBAdaptor.QueryParams.UID.key(), new ArrayList<>(transformedFromFileIds));
try (DBIterator<File> iterator = fileDBAdaptor.iterator(query, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(
FileDBAdaptor.QueryParams.INDEX.key(), FileDBAdaptor.QueryParams.UID.key())))) {
while (iterator.hasNext()) {
File next = iterator.next();
String status = next.getIndex().getStatus().getName();
switch (status) {
case FileIndex.IndexStatus.READY:
// If they are already ready, we only need to remove the reference to the transformed files as they will be
// removed
next.getIndex().setTransformedFile(null);
break;
case FileIndex.IndexStatus.TRANSFORMED:
// We need to remove the reference to the transformed files and change their status from TRANSFORMED to NONE
next.getIndex().setTransformedFile(null);
next.getIndex().getStatus().setName(FileIndex.IndexStatus.NONE);
break;
case FileIndex.IndexStatus.NONE:
case FileIndex.IndexStatus.DELETED:
break;
default:
throw new CatalogException("Cannot delete files that are in use in storage.");
}
}
}
}
return filesToAnalyse;
}
public FacetQueryResult facet(String studyStr, Query query, QueryOptions queryOptions, boolean defaultStats, String sessionId)
throws CatalogException, IOException {
ParamUtils.defaultObject(query, Query::new);
ParamUtils.defaultObject(queryOptions, QueryOptions::new);
if (defaultStats || StringUtils.isEmpty(queryOptions.getString(QueryOptions.FACET))) {
String facet = queryOptions.getString(QueryOptions.FACET);
queryOptions.put(QueryOptions.FACET, StringUtils.isNotEmpty(facet) ? defaultFacet + ";" + facet : defaultFacet);
}
CatalogSolrManager catalogSolrManager = new CatalogSolrManager(catalogManager);
String userId = userManager.getUserId(sessionId);
// We need to add variableSets and groups to avoid additional queries as it will be used in the catalogSolrManager
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId, new QueryOptions(QueryOptions.INCLUDE,
Arrays.asList(StudyDBAdaptor.QueryParams.VARIABLE_SET.key(), StudyDBAdaptor.QueryParams.GROUPS.key())));
AnnotationUtils.fixQueryAnnotationSearch(study, userId, query, authorizationManager);
return catalogSolrManager.facetedQuery(study, CatalogSolrManager.FILE_SOLR_COLLECTION, query, queryOptions, userId);
}
private void updateIndexStatusAfterDeletionOfTransformedFile(long studyId, File file) throws CatalogDBException {
if (file.getType() == File.Type.FILE && (file.getRelatedFiles() == null || file.getRelatedFiles().isEmpty())) {
return;
}
// We check if any of the files to be removed are transformation files
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + file.getPath() + "*")
.append(FileDBAdaptor.QueryParams.RELATED_FILES_RELATION.key(), File.RelatedFile.Relation.PRODUCED_FROM);
QueryResult<File> fileQR = fileDBAdaptor.get(query, new QueryOptions(QueryOptions.INCLUDE,
FileDBAdaptor.QueryParams.RELATED_FILES.key()));
if (fileQR.getNumResults() > 0) {
// Among the files to be deleted / unlinked, there are transformed files. We need to check that these files are not being used
// anymore.
Set<Long> fileIds = new HashSet<>();
for (File transformedFile : fileQR.getResult()) {
fileIds.addAll(
transformedFile.getRelatedFiles().stream()
.filter(myFile -> myFile.getRelation() == File.RelatedFile.Relation.PRODUCED_FROM)
.map(File.RelatedFile::getFileId)
.collect(Collectors.toSet())
);
}
// Update the original files to remove the transformed file
query = new Query(FileDBAdaptor.QueryParams.UID.key(), new ArrayList<>(fileIds));
Map<Long, FileIndex> filesToUpdate;
try (DBIterator<File> iterator = fileDBAdaptor.iterator(query, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(
FileDBAdaptor.QueryParams.INDEX.key(), FileDBAdaptor.QueryParams.UID.key())))) {
filesToUpdate = new HashMap<>();
while (iterator.hasNext()) {
File next = iterator.next();
String status = next.getIndex().getStatus().getName();
switch (status) {
case FileIndex.IndexStatus.READY:
// If they are already ready, we only need to remove the reference to the transformed files as they will be
// removed
next.getIndex().setTransformedFile(null);
filesToUpdate.put(next.getUid(), next.getIndex());
break;
case FileIndex.IndexStatus.TRANSFORMED:
// We need to remove the reference to the transformed files and change their status from TRANSFORMED to NONE
next.getIndex().setTransformedFile(null);
next.getIndex().getStatus().setName(FileIndex.IndexStatus.NONE);
filesToUpdate.put(next.getUid(), next.getIndex());
break;
default:
break;
}
}
}
for (Map.Entry<Long, FileIndex> indexEntry : filesToUpdate.entrySet()) {
fileDBAdaptor.update(indexEntry.getKey(), new ObjectMap(FileDBAdaptor.QueryParams.INDEX.key(), indexEntry.getValue()),
QueryOptions.empty());
}
}
}
/**
* Create the parent directories that are needed.
*
* @param study study where they will be created.
* @param userId user that is creating the parents.
* @param studyURI Base URI where the created folders will be pointing to. (base physical location)
* @param path Path used in catalog as a virtual location. (whole bunch of directories inside the virtual
* location in catalog)
* @param checkPermissions Boolean indicating whether to check if the user has permissions to create a folder in the first directory
* that is available in catalog.
* @throws CatalogDBException
*/
private void createParents(Study study, String userId, URI studyURI, Path path, boolean checkPermissions) throws CatalogException {
if (path == null) {
if (checkPermissions) {
authorizationManager.checkStudyPermission(study.getUid(), userId, StudyAclEntry.StudyPermissions.WRITE_FILES);
}
return;
}
String stringPath = path.toString();
if (("/").equals(stringPath)) {
return;
}
logger.info("Path: {}", stringPath);
if (stringPath.startsWith("/")) {
stringPath = stringPath.substring(1);
}
if (!stringPath.endsWith("/")) {
stringPath = stringPath + "/";
}
// Check if the folder exists
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), stringPath);
if (fileDBAdaptor.count(query).first() == 0) {
createParents(study, userId, studyURI, path.getParent(), checkPermissions);
} else {
if (checkPermissions) {
long fileId = fileDBAdaptor.getId(study.getUid(), stringPath);
authorizationManager.checkFilePermission(study.getUid(), fileId, userId, FileAclEntry.FilePermissions.WRITE);
}
return;
}
String parentPath = getParentPath(stringPath);
long parentFileId = fileDBAdaptor.getId(study.getUid(), parentPath);
// We obtain the permissions set in the parent folder and set them to the file or folder being created
QueryResult<FileAclEntry> allFileAcls = authorizationManager.getAllFileAcls(study.getUid(), parentFileId, userId, checkPermissions);
URI completeURI = Paths.get(studyURI).resolve(path).toUri();
// Create the folder in catalog
File folder = new File(path.getFileName().toString(), File.Type.DIRECTORY, File.Format.PLAIN, File.Bioformat.NONE, completeURI,
stringPath, null, TimeUtils.getTime(), TimeUtils.getTime(), "", new File.FileStatus(File.FileStatus.READY), false, 0, null,
new Experiment(), Collections.emptyList(), new Job(), Collections.emptyList(), null,
catalogManager.getStudyManager().getCurrentRelease(study, userId), Collections.emptyList(), null, null);
folder.setUuid(UUIDUtils.generateOpenCGAUUID(UUIDUtils.Entity.FILE));
checkHooks(folder, study.getFqn(), HookConfiguration.Stage.CREATE);
QueryResult<File> queryResult = fileDBAdaptor.insert(study.getUid(), folder, Collections.emptyList(), new QueryOptions());
// Propagate ACLs
if (allFileAcls != null && allFileAcls.getNumResults() > 0) {
authorizationManager.replicateAcls(study.getUid(), Arrays.asList(queryResult.first().getUid()), allFileAcls.getResult(),
Entity.FILE);
}
}
private QueryResult<File> privateLink(Study study, URI uriOrigin, String pathDestiny, ObjectMap params, String sessionId)
throws CatalogException, IOException {
params = ParamUtils.defaultObject(params, ObjectMap::new);
CatalogIOManager ioManager = catalogIOManagerFactory.get(uriOrigin);
if (!ioManager.exists(uriOrigin)) {
throw new CatalogIOException("File " + uriOrigin + " does not exist");
}
final URI normalizedUri;
try {
normalizedUri = UriUtils.createUri(uriOrigin.normalize().getPath());
} catch (URISyntaxException e) {
throw new CatalogException(e);
}
String userId = userManager.getUserId(sessionId);
authorizationManager.checkStudyPermission(study.getUid(), userId, StudyAclEntry.StudyPermissions.WRITE_FILES);
pathDestiny = ParamUtils.defaultString(pathDestiny, "");
if (pathDestiny.length() == 1 && (pathDestiny.equals(".") || pathDestiny.equals("/"))) {
pathDestiny = "";
} else {
if (pathDestiny.startsWith("/")) {
pathDestiny = pathDestiny.substring(1);
}
if (!pathDestiny.isEmpty() && !pathDestiny.endsWith("/")) {
pathDestiny = pathDestiny + "/";
}
}
String externalPathDestinyStr;
if (Paths.get(normalizedUri).toFile().isDirectory()) {
externalPathDestinyStr = Paths.get(pathDestiny).resolve(Paths.get(normalizedUri).getFileName()).toString() + "/";
} else {
externalPathDestinyStr = Paths.get(pathDestiny).resolve(Paths.get(normalizedUri).getFileName()).toString();
}
// Check if the path already exists and is not external
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), "!=" + File.FileStatus.TRASHED + ";!=" + Status.DELETED + ";!="
+ File.FileStatus.REMOVED)
.append(FileDBAdaptor.QueryParams.PATH.key(), externalPathDestinyStr)
.append(FileDBAdaptor.QueryParams.EXTERNAL.key(), false);
if (fileDBAdaptor.count(query).first() > 0) {
throw new CatalogException("Cannot link to " + externalPathDestinyStr + ". The path already existed and is not external.");
}
// Check if the uri was already linked to that same path
query = new Query()
.append(FileDBAdaptor.QueryParams.URI.key(), normalizedUri)
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), "!=" + File.FileStatus.TRASHED + ";!=" + Status.DELETED + ";!="
+ File.FileStatus.REMOVED)
.append(FileDBAdaptor.QueryParams.PATH.key(), externalPathDestinyStr)
.append(FileDBAdaptor.QueryParams.EXTERNAL.key(), true);
if (fileDBAdaptor.count(query).first() > 0) {
// Create a regular expression on URI to return everything linked from that URI
query.put(FileDBAdaptor.QueryParams.URI.key(), "~^" + normalizedUri);
query.remove(FileDBAdaptor.QueryParams.PATH.key());
// Limit the number of results and only some fields
QueryOptions queryOptions = new QueryOptions()
.append(QueryOptions.LIMIT, 100);
return fileDBAdaptor.get(query, queryOptions);
}
// Check if the uri was linked to other path
query = new Query()
.append(FileDBAdaptor.QueryParams.URI.key(), normalizedUri)
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), "!=" + File.FileStatus.TRASHED + ";!=" + Status.DELETED + ";!="
+ File.FileStatus.REMOVED)
.append(FileDBAdaptor.QueryParams.EXTERNAL.key(), true);
if (fileDBAdaptor.count(query).first() > 0) {
QueryOptions queryOptions = new QueryOptions(QueryOptions.INCLUDE, FileDBAdaptor.QueryParams.PATH.key());
String path = fileDBAdaptor.get(query, queryOptions).first().getPath();
throw new CatalogException(normalizedUri + " was already linked to other path: " + path);
}
boolean parents = params.getBoolean("parents", false);
// FIXME: Implement resync
boolean resync = params.getBoolean("resync", false);
String description = params.getString("description", "");
String checksum = params.getString(FileDBAdaptor.QueryParams.CHECKSUM.key(), "");
// Because pathDestiny can be null, we will use catalogPath as the virtual destiny where the files will be located in catalog.
Path catalogPath = Paths.get(pathDestiny);
if (pathDestiny.isEmpty()) {
// If no destiny is given, everything will be linked to the root folder of the study.
authorizationManager.checkStudyPermission(study.getUid(), userId, StudyAclEntry.StudyPermissions.WRITE_FILES);
} else {
// Check if the folder exists
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), pathDestiny);
if (fileDBAdaptor.count(query).first() == 0) {
if (parents) {
// Get the base URI where the files are located in the study
URI studyURI = study.getUri();
createParents(study, userId, studyURI, catalogPath, true);
// Create them in the disk
// URI directory = Paths.get(studyURI).resolve(catalogPath).toUri();
// catalogIOManagerFactory.get(directory).createDirectory(directory, true);
} else {
throw new CatalogException("The path " + catalogPath + " does not exist in catalog.");
}
} else {
// Check if the user has permissions to link files in the directory
long fileId = fileDBAdaptor.getId(study.getUid(), pathDestiny);
authorizationManager.checkFilePermission(study.getUid(), fileId, userId, FileAclEntry.FilePermissions.WRITE);
}
}
Path pathOrigin = Paths.get(normalizedUri);
Path externalPathDestiny = Paths.get(externalPathDestinyStr);
if (Paths.get(normalizedUri).toFile().isFile()) {
// Check if there is already a file in the same path
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), externalPathDestinyStr);
// Create the file
if (fileDBAdaptor.count(query).first() == 0) {
long size = Files.size(Paths.get(normalizedUri));
String parentPath = getParentPath(externalPathDestinyStr);
long parentFileId = fileDBAdaptor.getId(study.getUid(), parentPath);
// We obtain the permissions set in the parent folder and set them to the file or folder being created
QueryResult<FileAclEntry> allFileAcls = authorizationManager.getAllFileAcls(study.getUid(), parentFileId, userId, true);
File subfile = new File(externalPathDestiny.getFileName().toString(), File.Type.FILE, File.Format.UNKNOWN,
File.Bioformat.NONE, normalizedUri, externalPathDestinyStr, checksum, TimeUtils.getTime(), TimeUtils.getTime(),
description, new File.FileStatus(File.FileStatus.READY), true, size, null, new Experiment(),
Collections.emptyList(), new Job(), Collections.emptyList(), null,
catalogManager.getStudyManager().getCurrentRelease(study, userId), Collections.emptyList(), Collections.emptyMap(),
Collections.emptyMap());
subfile.setUuid(UUIDUtils.generateOpenCGAUUID(UUIDUtils.Entity.FILE));
checkHooks(subfile, study.getFqn(), HookConfiguration.Stage.CREATE);
QueryResult<File> queryResult = fileDBAdaptor.insert(study.getUid(), subfile, Collections.emptyList(), new QueryOptions());
// Propagate ACLs
if (allFileAcls != null && allFileAcls.getNumResults() > 0) {
authorizationManager.replicateAcls(study.getUid(), Arrays.asList(queryResult.first().getUid()), allFileAcls.getResult(),
Entity.FILE);
}
File file = this.file.setMetadataInformation(queryResult.first(), queryResult.first().getUri(),
new QueryOptions(), sessionId, false);
queryResult.setResult(Arrays.asList(file));
// If it is a transformed file, we will try to link it with the correspondent original file
try {
if (isTransformedFile(file.getName())) {
matchUpVariantFiles(study.getFqn(), Arrays.asList(file), sessionId);
}
} catch (CatalogException e) {
logger.warn("Matching avro to variant file: {}", e.getMessage());
}
return queryResult;
} else {
throw new CatalogException("Cannot link " + externalPathDestiny.getFileName().toString() + ". A file with the same name "
+ "was found in the same path.");
}
} else {
// This list will contain the list of transformed files detected during the link
List<File> transformedFiles = new ArrayList<>();
// We remove the / at the end for replacement purposes in the walkFileTree
String finalExternalPathDestinyStr = externalPathDestinyStr.substring(0, externalPathDestinyStr.length() - 1);
// Link all the files and folders present in the uri
Files.walkFileTree(pathOrigin, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
try {
String destinyPath = dir.toString().replace(Paths.get(normalizedUri).toString(), finalExternalPathDestinyStr);
if (!destinyPath.isEmpty() && !destinyPath.endsWith("/")) {
destinyPath += "/";
}
if (destinyPath.startsWith("/")) {
destinyPath = destinyPath.substring(1);
}
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), destinyPath);
if (fileDBAdaptor.count(query).first() == 0) {
// If the folder does not exist, we create it
String parentPath = getParentPath(destinyPath);
long parentFileId = fileDBAdaptor.getId(study.getUid(), parentPath);
// We obtain the permissions set in the parent folder and set them to the file or folder being created
QueryResult<FileAclEntry> allFileAcls;
try {
allFileAcls = authorizationManager.getAllFileAcls(study.getUid(), parentFileId, userId, true);
} catch (CatalogException e) {
throw new RuntimeException(e);
}
File folder = new File(dir.getFileName().toString(), File.Type.DIRECTORY, File.Format.PLAIN,
File.Bioformat.NONE, dir.toUri(), destinyPath, null, TimeUtils.getTime(),
TimeUtils.getTime(), description, new File.FileStatus(File.FileStatus.READY), true, 0, null,
new Experiment(), Collections.emptyList(), new Job(), Collections.emptyList(),
null, catalogManager.getStudyManager().getCurrentRelease(study, userId), Collections.emptyList(),
Collections.emptyMap(), Collections.emptyMap());
folder.setUuid(UUIDUtils.generateOpenCGAUUID(UUIDUtils.Entity.FILE));
checkHooks(folder, study.getFqn(), HookConfiguration.Stage.CREATE);
QueryResult<File> queryResult = fileDBAdaptor.insert(study.getUid(), folder, Collections.emptyList(),
new QueryOptions());
// Propagate ACLs
if (allFileAcls != null && allFileAcls.getNumResults() > 0) {
authorizationManager.replicateAcls(study.getUid(), Arrays.asList(queryResult.first().getUid()),
allFileAcls.getResult(), Entity.FILE);
}
}
} catch (CatalogException e) {
logger.error("An error occurred when trying to create folder {}", dir.toString());
// e.printStackTrace();
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException {
try {
String destinyPath = filePath.toString().replace(Paths.get(normalizedUri).toString(), finalExternalPathDestinyStr);
if (destinyPath.startsWith("/")) {
destinyPath = destinyPath.substring(1);
}
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), destinyPath);
if (fileDBAdaptor.count(query).first() == 0) {
long size = Files.size(filePath);
// If the file does not exist, we create it
String parentPath = getParentPath(destinyPath);
long parentFileId = fileDBAdaptor.getId(study.getUid(), parentPath);
// We obtain the permissions set in the parent folder and set them to the file or folder being created
QueryResult<FileAclEntry> allFileAcls;
try {
allFileAcls = authorizationManager.getAllFileAcls(study.getUid(), parentFileId, userId, true);
} catch (CatalogException e) {
throw new RuntimeException(e);
}
File subfile = new File(filePath.getFileName().toString(), File.Type.FILE, File.Format.UNKNOWN,
File.Bioformat.NONE, filePath.toUri(), destinyPath, null, TimeUtils.getTime(),
TimeUtils.getTime(), description, new File.FileStatus(File.FileStatus.READY), true, size, null,
new Experiment(), Collections.emptyList(), new Job(), Collections.emptyList(),
null, catalogManager.getStudyManager().getCurrentRelease(study, userId), Collections.emptyList(),
Collections.emptyMap(), Collections.emptyMap());
subfile.setUuid(UUIDUtils.generateOpenCGAUUID(UUIDUtils.Entity.FILE));
checkHooks(subfile, study.getFqn(), HookConfiguration.Stage.CREATE);
QueryResult<File> queryResult = fileDBAdaptor.insert(study.getUid(), subfile, Collections.emptyList(),
new QueryOptions());
// Propagate ACLs
if (allFileAcls != null && allFileAcls.getNumResults() > 0) {
authorizationManager.replicateAcls(study.getUid(), Arrays.asList(queryResult.first().getUid()),
allFileAcls.getResult(), Entity.FILE);
}
File file = FileManager.this.file.setMetadataInformation(queryResult.first(), queryResult.first().getUri(),
new QueryOptions(), sessionId, false);
if (isTransformedFile(file.getName())) {
logger.info("Detected transformed file {}", file.getPath());
transformedFiles.add(file);
}
} else {
throw new CatalogException("Cannot link the file " + filePath.getFileName().toString()
+ ". There is already a file in the path " + destinyPath + " with the same name.");
}
} catch (CatalogException e) {
logger.error(e.getMessage());
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.SKIP_SUBTREE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
// Try to link transformed files with their corresponding original files if any
try {
if (transformedFiles.size() > 0) {
matchUpVariantFiles(study.getFqn(), transformedFiles, sessionId);
}
} catch (CatalogException e) {
logger.warn("Matching avro to variant file: {}", e.getMessage());
}
// Check if the uri was already linked to that same path
query = new Query()
.append(FileDBAdaptor.QueryParams.URI.key(), "~^" + normalizedUri)
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), "!=" + File.FileStatus.TRASHED + ";!=" + Status.DELETED + ";!="
+ File.FileStatus.REMOVED)
.append(FileDBAdaptor.QueryParams.EXTERNAL.key(), true);
// Limit the number of results and only some fields
QueryOptions queryOptions = new QueryOptions()
.append(QueryOptions.LIMIT, 100);
return fileDBAdaptor.get(query, queryOptions);
}
}
private void checkHooks(File file, String fqn, HookConfiguration.Stage stage) throws CatalogException {
Map<String, Map<String, List<HookConfiguration>>> hooks = this.configuration.getHooks();
if (hooks != null && hooks.containsKey(fqn)) {
Map<String, List<HookConfiguration>> entityHookMap = hooks.get(fqn);
List<HookConfiguration> hookList = null;
if (entityHookMap.containsKey(MongoDBAdaptorFactory.FILE_COLLECTION)) {
hookList = entityHookMap.get(MongoDBAdaptorFactory.FILE_COLLECTION);
} else if (entityHookMap.containsKey(MongoDBAdaptorFactory.FILE_COLLECTION.toUpperCase())) {
hookList = entityHookMap.get(MongoDBAdaptorFactory.FILE_COLLECTION.toUpperCase());
}
// We check the hook list
if (hookList != null) {
for (HookConfiguration hookConfiguration : hookList) {
if (hookConfiguration.getStage() != stage) {
continue;
}
String field = hookConfiguration.getField();
if (StringUtils.isEmpty(field)) {
logger.warn("Missing 'field' field from hook configuration");
continue;
}
field = field.toLowerCase();
String filterValue = hookConfiguration.getValue();
if (StringUtils.isEmpty(filterValue)) {
logger.warn("Missing 'value' field from hook configuration");
continue;
}
String value = null;
switch (field) {
case "name":
value = file.getName();
break;
case "format":
value = file.getFormat().name();
break;
case "bioformat":
value = file.getFormat().name();
break;
case "path":
value = file.getPath();
break;
case "description":
value = file.getDescription();
break;
// TODO: At some point, we will also have to consider any field that is not a String
// case "size":
// value = file.getSize();
// break;
default:
break;
}
if (value == null) {
continue;
}
String filterNewValue = hookConfiguration.getWhat();
if (StringUtils.isEmpty(filterNewValue)) {
logger.warn("Missing 'what' field from hook configuration");
continue;
}
String filterWhere = hookConfiguration.getWhere();
if (StringUtils.isEmpty(filterWhere)) {
logger.warn("Missing 'where' field from hook configuration");
continue;
}
filterWhere = filterWhere.toLowerCase();
if (filterValue.startsWith("~")) {
// Regular expression
if (!value.matches(filterValue.substring(1))) {
// If it doesn't match, we will check the next hook of the loop
continue;
}
} else {
if (!value.equals(filterValue)) {
// If it doesn't match, we will check the next hook of the loop
continue;
}
}
// The value matched, so we will perform the action desired by the user
if (hookConfiguration.getAction() == HookConfiguration.Action.ABORT) {
throw new CatalogException("A hook to abort the insertion matched");
}
// We check the field the user wants to update
if (filterWhere.equals(FileDBAdaptor.QueryParams.DESCRIPTION.key())) {
switch (hookConfiguration.getAction()) {
case ADD:
case SET:
file.setDescription(hookConfiguration.getWhat());
break;
case REMOVE:
file.setDescription("");
break;
default:
break;
}
} else if (filterWhere.equals(FileDBAdaptor.QueryParams.TAGS.key())) {
switch (hookConfiguration.getAction()) {
case ADD:
List<String> values;
if (hookConfiguration.getWhat().contains(",")) {
values = Arrays.asList(hookConfiguration.getWhat().split(","));
} else {
values = Collections.singletonList(hookConfiguration.getWhat());
}
List<String> tagsCopy = new ArrayList<>();
if (file.getTags() != null) {
tagsCopy.addAll(file.getTags());
}
tagsCopy.addAll(values);
file.setTags(tagsCopy);
break;
case SET:
if (hookConfiguration.getWhat().contains(",")) {
values = Arrays.asList(hookConfiguration.getWhat().split(","));
} else {
values = Collections.singletonList(hookConfiguration.getWhat());
}
file.setTags(values);
break;
case REMOVE:
file.setTags(Collections.emptyList());
break;
default:
break;
}
} else if (filterWhere.startsWith(FileDBAdaptor.QueryParams.STATS.key())) {
String[] split = StringUtils.split(filterWhere, ".", 2);
String statsField = null;
if (split.length == 2) {
statsField = split[1];
}
switch (hookConfiguration.getAction()) {
case ADD:
if (statsField == null) {
logger.error("Cannot add a value to {} directly. Expected {}.<subfield>",
FileDBAdaptor.QueryParams.STATS.key(), FileDBAdaptor.QueryParams.STATS.key());
continue;
}
List<String> values;
if (hookConfiguration.getWhat().contains(",")) {
values = Arrays.asList(hookConfiguration.getWhat().split(","));
} else {
values = Collections.singletonList(hookConfiguration.getWhat());
}
Object currentStatsValue = file.getStats().get(statsField);
if (currentStatsValue == null) {
file.getStats().put(statsField, values);
} else if (currentStatsValue instanceof Collection) {
((List) currentStatsValue).addAll(values);
} else {
logger.error("Cannot add a value to {} if it is not an array", filterWhere);
continue;
}
break;
case SET:
if (statsField == null) {
logger.error("Cannot set a value to {} directly. Expected {}.<subfield>",
FileDBAdaptor.QueryParams.STATS.key(), FileDBAdaptor.QueryParams.STATS.key());
continue;
}
if (hookConfiguration.getWhat().contains(",")) {
values = Arrays.asList(hookConfiguration.getWhat().split(","));
} else {
values = Collections.singletonList(hookConfiguration.getWhat());
}
file.getStats().put(statsField, values);
break;
case REMOVE:
if (statsField == null) {
file.setStats(Collections.emptyMap());
} else {
file.getStats().remove(statsField);
}
break;
default:
break;
}
} else if (filterWhere.startsWith(FileDBAdaptor.QueryParams.ATTRIBUTES.key())) {
String[] split = StringUtils.split(filterWhere, ".", 2);
String attributesField = null;
if (split.length == 2) {
attributesField = split[1];
}
switch (hookConfiguration.getAction()) {
case ADD:
if (attributesField == null) {
logger.error("Cannot add a value to {} directly. Expected {}.<subfield>",
FileDBAdaptor.QueryParams.ATTRIBUTES.key(), FileDBAdaptor.QueryParams.ATTRIBUTES.key());
continue;
}
List<String> values;
if (hookConfiguration.getWhat().contains(",")) {
values = Arrays.asList(hookConfiguration.getWhat().split(","));
} else {
values = Collections.singletonList(hookConfiguration.getWhat());
}
Object currentStatsValue = file.getAttributes().get(attributesField);
if (currentStatsValue == null) {
file.getAttributes().put(attributesField, values);
} else if (currentStatsValue instanceof Collection) {
((List) currentStatsValue).addAll(values);
} else {
logger.error("Cannot add a value to {} if it is not an array", filterWhere);
continue;
}
break;
case SET:
if (attributesField == null) {
logger.error("Cannot set a value to {} directly. Expected {}.<subfield>",
FileDBAdaptor.QueryParams.ATTRIBUTES.key(), FileDBAdaptor.QueryParams.ATTRIBUTES.key());
continue;
}
if (hookConfiguration.getWhat().contains(",")) {
values = Arrays.asList(hookConfiguration.getWhat().split(","));
} else {
values = Collections.singletonList(hookConfiguration.getWhat());
}
file.getAttributes().put(attributesField, values);
break;
case REMOVE:
if (attributesField == null) {
file.setAttributes(Collections.emptyMap());
} else {
file.getAttributes().remove(attributesField);
}
break;
default:
break;
}
} else {
logger.error("{} field cannot be updated. Please, check the hook configured.", hookConfiguration.getWhere());
}
}
}
}
}
private URI getStudyUri(long studyId) throws CatalogException {
return studyDBAdaptor.get(studyId, INCLUDE_STUDY_URI).first().getUri();
}
private enum CheckPath {
FREE_PATH, FILE_EXISTS, DIRECTORY_EXISTS
}
private CheckPath checkPathExists(String path, long studyId) throws CatalogDBException {
String myPath = path;
if (myPath.endsWith("/")) {
myPath = myPath.substring(0, myPath.length() - 1);
}
// We first look for any file called the same way the directory needs to be called
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), myPath);
QueryResult<Long> fileQueryResult = fileDBAdaptor.count(query);
if (fileQueryResult.first() > 0) {
return CheckPath.FILE_EXISTS;
}
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), myPath + "/");
fileQueryResult = fileDBAdaptor.count(query);
return fileQueryResult.first() > 0 ? CheckPath.DIRECTORY_EXISTS : CheckPath.FREE_PATH;
}
}
| opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FileManager.java | /*
* Copyright 2015-2017 OpenCB
*
* 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.opencb.opencga.catalog.managers;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.opencb.biodata.models.variant.VariantFileMetadata;
import org.opencb.biodata.models.variant.stats.VariantSetStats;
import org.opencb.commons.datastore.core.ObjectMap;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.datastore.core.QueryResult;
import org.opencb.commons.datastore.core.result.Error;
import org.opencb.commons.datastore.core.result.FacetQueryResult;
import org.opencb.commons.datastore.core.result.WriteResult;
import org.opencb.commons.utils.CollectionUtils;
import org.opencb.commons.utils.FileUtils;
import org.opencb.opencga.catalog.audit.AuditManager;
import org.opencb.opencga.catalog.audit.AuditRecord;
import org.opencb.opencga.catalog.auth.authorization.AuthorizationManager;
import org.opencb.opencga.catalog.db.DBAdaptorFactory;
import org.opencb.opencga.catalog.db.api.*;
import org.opencb.opencga.catalog.db.mongodb.MongoDBAdaptorFactory;
import org.opencb.opencga.catalog.exceptions.CatalogDBException;
import org.opencb.opencga.catalog.exceptions.CatalogException;
import org.opencb.opencga.catalog.exceptions.CatalogIOException;
import org.opencb.opencga.catalog.exceptions.CatalogParameterException;
import org.opencb.opencga.catalog.io.CatalogIOManager;
import org.opencb.opencga.catalog.io.CatalogIOManagerFactory;
import org.opencb.opencga.catalog.monitor.daemons.IndexDaemon;
import org.opencb.opencga.catalog.stats.solr.CatalogSolrManager;
import org.opencb.opencga.catalog.utils.*;
import org.opencb.opencga.core.common.Entity;
import org.opencb.opencga.core.common.TimeUtils;
import org.opencb.opencga.core.common.UriUtils;
import org.opencb.opencga.core.config.Configuration;
import org.opencb.opencga.core.config.HookConfiguration;
import org.opencb.opencga.core.models.*;
import org.opencb.opencga.core.models.File;
import org.opencb.opencga.core.models.acls.permissions.FileAclEntry;
import org.opencb.opencga.core.models.acls.permissions.StudyAclEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.opencb.opencga.catalog.auth.authorization.CatalogAuthorizationManager.checkPermissions;
import static org.opencb.opencga.catalog.utils.FileMetadataReader.VARIANT_FILE_STATS;
import static org.opencb.opencga.core.common.JacksonUtils.getDefaultObjectMapper;
/**
* @author Jacobo Coll <[email protected]>
*/
public class FileManager extends AnnotationSetManager<File> {
private static final QueryOptions INCLUDE_STUDY_URI;
private static final QueryOptions INCLUDE_FILE_URI_PATH;
private static final Comparator<File> ROOT_FIRST_COMPARATOR;
private static final Comparator<File> ROOT_LAST_COMPARATOR;
protected static Logger logger;
private FileMetadataReader file;
private UserManager userManager;
public static final String SKIP_TRASH = "SKIP_TRASH";
public static final String DELETE_EXTERNAL_FILES = "DELETE_EXTERNAL_FILES";
public static final String FORCE_DELETE = "FORCE_DELETE";
public static final String GET_NON_DELETED_FILES = Status.READY + "," + File.FileStatus.TRASHED + "," + File.FileStatus.STAGE + ","
+ File.FileStatus.MISSING;
public static final String GET_NON_TRASHED_FILES = Status.READY + "," + File.FileStatus.STAGE + "," + File.FileStatus.MISSING;
private final String defaultFacet = "creationYear>>creationMonth;format;bioformat;format>>bioformat;status;"
+ "size[0..214748364800]:10737418240;numSamples[0..10]:1";
static {
INCLUDE_STUDY_URI = new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.URI.key());
INCLUDE_FILE_URI_PATH = new QueryOptions(QueryOptions.INCLUDE,
Arrays.asList(FileDBAdaptor.QueryParams.URI.key(), FileDBAdaptor.QueryParams.PATH.key(),
FileDBAdaptor.QueryParams.EXTERNAL.key()));
ROOT_FIRST_COMPARATOR = (f1, f2) -> (f1.getPath() == null ? 0 : f1.getPath().length())
- (f2.getPath() == null ? 0 : f2.getPath().length());
ROOT_LAST_COMPARATOR = (f1, f2) -> (f2.getPath() == null ? 0 : f2.getPath().length())
- (f1.getPath() == null ? 0 : f1.getPath().length());
logger = LoggerFactory.getLogger(FileManager.class);
}
FileManager(AuthorizationManager authorizationManager, AuditManager auditManager, CatalogManager catalogManager,
DBAdaptorFactory catalogDBAdaptorFactory, CatalogIOManagerFactory ioManagerFactory, Configuration configuration) {
super(authorizationManager, auditManager, catalogManager, catalogDBAdaptorFactory, ioManagerFactory, configuration);
file = new FileMetadataReader(this.catalogManager);
this.userManager = catalogManager.getUserManager();
}
public URI getUri(File file) throws CatalogException {
ParamUtils.checkObj(file, "File");
if (file.getUri() != null) {
return file.getUri();
} else {
QueryResult<File> fileQueryResult = fileDBAdaptor.get(file.getUid(), INCLUDE_STUDY_URI);
if (fileQueryResult.getNumResults() == 0) {
throw new CatalogException("File " + file.getUid() + " not found");
}
return fileQueryResult.first().getUri();
}
}
@Deprecated
public URI getUri(long studyId, String filePath) throws CatalogException {
ParamUtils.checkObj(filePath, "filePath");
List<File> parents = getParents(false, INCLUDE_FILE_URI_PATH, filePath, studyId).getResult();
for (File parent : parents) {
if (parent.getUri() != null) {
if (parent.isExternal()) {
throw new CatalogException("Cannot upload files to an external folder");
}
String relativePath = filePath.replaceFirst(parent.getPath(), "");
return Paths.get(parent.getUri()).resolve(relativePath).toUri();
}
}
URI studyUri = getStudyUri(studyId);
return filePath.isEmpty()
? studyUri
: catalogIOManagerFactory.get(studyUri).getFileUri(studyUri, filePath);
}
public Study getStudy(File file, String sessionId) throws CatalogException {
ParamUtils.checkObj(file, "file");
ParamUtils.checkObj(sessionId, "session id");
if (file.getStudyUid() <= 0) {
throw new CatalogException("Missing study uid field in file");
}
String user = catalogManager.getUserManager().getUserId(sessionId);
Query query = new Query(StudyDBAdaptor.QueryParams.UID.key(), file.getStudyUid());
QueryResult<Study> studyQueryResult = studyDBAdaptor.get(query, QueryOptions.empty(), user);
if (studyQueryResult.getNumResults() == 1) {
return studyQueryResult.first();
} else {
authorizationManager.checkCanViewStudy(file.getStudyUid(), user);
throw new CatalogException("Incorrect study uid");
}
}
public void matchUpVariantFiles(String studyStr, List<File> transformedFiles, String sessionId) throws CatalogException {
String userId = catalogManager.getUserManager().getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
for (File transformedFile : transformedFiles) {
authorizationManager.checkFilePermission(study.getUid(), transformedFile.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
String variantPathName = getOriginalFile(transformedFile.getPath());
if (variantPathName == null) {
// Skip the file.
logger.warn("The file {} is not a variant transformed file", transformedFile.getName());
continue;
}
// Search in the same path
logger.info("Looking for vcf file in path {}", variantPathName);
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), variantPathName)
.append(FileDBAdaptor.QueryParams.BIOFORMAT.key(), File.Bioformat.VARIANT);
List<File> fileList = fileDBAdaptor.get(query, new QueryOptions()).getResult();
if (fileList.isEmpty()) {
// Search by name in the whole study
String variantFileName = getOriginalFile(transformedFile.getName());
logger.info("Looking for vcf file by name {}", variantFileName);
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.NAME.key(), variantFileName)
.append(FileDBAdaptor.QueryParams.BIOFORMAT.key(), File.Bioformat.VARIANT);
fileList = new ArrayList<>(fileDBAdaptor.get(query, new QueryOptions()).getResult());
// In case of finding more than one file, try to find the proper one.
if (fileList.size() > 1) {
// Discard files already with a transformed file.
fileList.removeIf(file -> file.getIndex() != null
&& file.getIndex().getTransformedFile() != null
&& file.getIndex().getTransformedFile().getId() != transformedFile.getUid());
}
if (fileList.size() > 1) {
// Discard files not transformed or indexed.
fileList.removeIf(file -> file.getIndex() == null
|| file.getIndex().getStatus() == null
|| file.getIndex().getStatus().getName() == null
|| file.getIndex().getStatus().getName().equals(FileIndex.IndexStatus.NONE));
}
}
if (fileList.size() != 1) {
// VCF file not found
logger.warn("The vcf file corresponding to the file " + transformedFile.getName() + " could not be found");
continue;
}
File vcf = fileList.get(0);
// Look for the json file. It should be in the same directory where the transformed file is.
String jsonPathName = getMetaFile(transformedFile.getPath());
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), jsonPathName)
.append(FileDBAdaptor.QueryParams.FORMAT.key(), File.Format.JSON);
fileList = fileDBAdaptor.get(query, new QueryOptions()).getResult();
if (fileList.size() != 1) {
// Skip. This should not ever happen
logger.warn("The json file corresponding to the file " + transformedFile.getName() + " could not be found");
continue;
}
File json = fileList.get(0);
/* Update relations */
File.RelatedFile producedFromRelation = new File.RelatedFile(vcf.getUid(), File.RelatedFile.Relation.PRODUCED_FROM);
// Update json file
logger.debug("Updating json relation");
List<File.RelatedFile> relatedFiles = ParamUtils.defaultObject(json.getRelatedFiles(), ArrayList::new);
// Do not add twice the same relation
if (!relatedFiles.contains(producedFromRelation)) {
relatedFiles.add(producedFromRelation);
ObjectMap params = new ObjectMap(FileDBAdaptor.QueryParams.RELATED_FILES.key(), relatedFiles);
fileDBAdaptor.update(json.getUid(), params, QueryOptions.empty());
}
// Update transformed file
logger.debug("Updating transformed relation");
relatedFiles = ParamUtils.defaultObject(transformedFile.getRelatedFiles(), ArrayList::new);
// Do not add twice the same relation
if (!relatedFiles.contains(producedFromRelation)) {
relatedFiles.add(producedFromRelation);
transformedFile.setRelatedFiles(relatedFiles);
ObjectMap params = new ObjectMap(FileDBAdaptor.QueryParams.RELATED_FILES.key(), relatedFiles);
fileDBAdaptor.update(transformedFile.getUid(), params, QueryOptions.empty());
}
// Update vcf file
logger.debug("Updating vcf relation");
FileIndex index = vcf.getIndex();
if (index.getTransformedFile() == null) {
index.setTransformedFile(new FileIndex.TransformedFile(transformedFile.getUid(), json.getUid()));
}
String status = FileIndex.IndexStatus.NONE;
if (vcf.getIndex() != null && vcf.getIndex().getStatus() != null && vcf.getIndex().getStatus().getName() != null) {
status = vcf.getIndex().getStatus().getName();
}
if (FileIndex.IndexStatus.NONE.equals(status)) {
// If TRANSFORMED, TRANSFORMING, etc, do not modify the index status
index.setStatus(new FileIndex.IndexStatus(FileIndex.IndexStatus.TRANSFORMED, "Found transformed file"));
}
ObjectMap params = new ObjectMap(FileDBAdaptor.QueryParams.INDEX.key(), index);
fileDBAdaptor.update(vcf.getUid(), params, QueryOptions.empty());
// Update variant stats
Path statsFile = Paths.get(json.getUri().getRawPath());
try (InputStream is = FileUtils.newInputStream(statsFile)) {
VariantFileMetadata fileMetadata = getDefaultObjectMapper().readValue(is, VariantFileMetadata.class);
VariantSetStats stats = fileMetadata.getStats();
params = new ObjectMap(FileDBAdaptor.QueryParams.STATS.key(), new ObjectMap(VARIANT_FILE_STATS, stats));
update(studyStr, vcf.getPath(), params, new QueryOptions(), sessionId);
} catch (IOException e) {
throw new CatalogException("Error reading file \"" + statsFile + "\"", e);
}
}
}
public void setStatus(String studyStr, String fileId, String status, String message, String sessionId) throws CatalogException {
MyResource<File> resource = getUid(fileId, studyStr, sessionId);
String userId = resource.getUser();
long fileUid = resource.getResource().getUid();
authorizationManager.checkFilePermission(resource.getStudy().getUid(), fileUid, userId, FileAclEntry.FilePermissions.WRITE);
if (status != null && !File.FileStatus.isValid(status)) {
throw new CatalogException("The status " + status + " is not valid file status.");
}
ObjectMap parameters = new ObjectMap();
parameters.putIfNotNull(FileDBAdaptor.QueryParams.STATUS_NAME.key(), status);
parameters.putIfNotNull(FileDBAdaptor.QueryParams.STATUS_MSG.key(), message);
fileDBAdaptor.update(fileUid, parameters, QueryOptions.empty());
auditManager.recordUpdate(AuditRecord.Resource.file, fileUid, userId, parameters, null, null);
}
public QueryResult<FileIndex> updateFileIndexStatus(File file, String newStatus, String message, String sessionId)
throws CatalogException {
return updateFileIndexStatus(file, newStatus, message, null, sessionId);
}
public QueryResult<FileIndex> updateFileIndexStatus(File file, String newStatus, String message, Integer release, String sessionId)
throws CatalogException {
String userId = catalogManager.getUserManager().getUserId(sessionId);
Long studyId = file.getStudyUid();
authorizationManager.checkFilePermission(studyId, file.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
FileIndex index = file.getIndex();
if (index != null) {
if (!FileIndex.IndexStatus.isValid(newStatus)) {
throw new CatalogException("The status " + newStatus + " is not a valid status.");
} else {
index.setStatus(new FileIndex.IndexStatus(newStatus, message));
}
} else {
index = new FileIndex(userId, TimeUtils.getTime(), new FileIndex.IndexStatus(newStatus), -1, new ObjectMap());
}
if (release != null) {
if (newStatus.equals(FileIndex.IndexStatus.READY)) {
index.setRelease(release);
}
}
ObjectMap params = new ObjectMap(FileDBAdaptor.QueryParams.INDEX.key(), index);
fileDBAdaptor.update(file.getUid(), params, QueryOptions.empty());
auditManager.recordUpdate(AuditRecord.Resource.file, file.getUid(), userId, params, null, null);
return new QueryResult<>("Update file index", 0, 1, 1, "", "", Arrays.asList(index));
}
@Deprecated
public QueryResult<File> getParents(long fileId, QueryOptions options, String sessionId) throws CatalogException {
QueryResult<File> fileQueryResult = fileDBAdaptor.get(fileId, new QueryOptions(QueryOptions.INCLUDE,
Arrays.asList(FileDBAdaptor.QueryParams.PATH.key(), FileDBAdaptor.QueryParams.STUDY_UID.key())));
if (fileQueryResult.getNumResults() == 0) {
return fileQueryResult;
}
String userId = userManager.getUserId(sessionId);
authorizationManager.checkFilePermission(fileQueryResult.first().getStudyUid(), fileId, userId, FileAclEntry.FilePermissions.VIEW);
return getParents(true, options, fileQueryResult.first().getPath(), fileQueryResult.first().getStudyUid());
}
public QueryResult<File> createFolder(String studyStr, String path, File.FileStatus status, boolean parents, String description,
QueryOptions options, String sessionId) throws CatalogException {
ParamUtils.checkPath(path, "folderPath");
options = ParamUtils.defaultObject(options, QueryOptions::new);
String userId = catalogManager.getUserManager().getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
if (path.startsWith("/")) {
path = path.substring(1);
}
if (!path.endsWith("/")) {
path = path + "/";
}
QueryResult<File> fileQueryResult;
switch (checkPathExists(path, study.getUid())) {
case FREE_PATH:
fileQueryResult = create(studyStr, File.Type.DIRECTORY, File.Format.NONE, File.Bioformat.NONE, path, null,
description, status, 0, -1, null, -1, null, null, parents, null, options, sessionId);
break;
case DIRECTORY_EXISTS:
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), path);
fileQueryResult = fileDBAdaptor.get(query, options, userId);
fileQueryResult.setWarningMsg("Folder was already created");
break;
case FILE_EXISTS:
default:
throw new CatalogException("A file with the same name of the folder already exists in Catalog");
}
fileQueryResult.setId("Create folder");
return fileQueryResult;
}
public QueryResult<File> createFile(String studyStr, String path, String description, boolean parents, String content,
String sessionId) throws CatalogException {
ParamUtils.checkPath(path, "filePath");
String userId = catalogManager.getUserManager().getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
if (path.startsWith("/")) {
path = path.substring(1);
}
switch (checkPathExists(path, study.getUid())) {
case FREE_PATH:
return create(studyStr, File.Type.FILE, File.Format.PLAIN, File.Bioformat.UNKNOWN, path, null, description,
new File.FileStatus(File.FileStatus.READY), 0, -1, null, -1, null, null, parents, content, new QueryOptions(),
sessionId);
case FILE_EXISTS:
case DIRECTORY_EXISTS:
default:
throw new CatalogException("A file or folder with the same name already exists in the path of Catalog");
}
}
public QueryResult<File> create(String studyStr, File.Type type, File.Format format, File.Bioformat bioformat, String path,
String creationDate, String description, File.FileStatus status, long size, long experimentId,
List<Sample> samples, long jobId, Map<String, Object> stats, Map<String, Object> attributes,
boolean parents, String content, QueryOptions options, String sessionId)
throws CatalogException {
File file = new File(type, format, bioformat, path, description, status, size, samples, jobId, null, stats, attributes);
return create(studyStr, file, parents, content, options, sessionId);
}
@Override
public QueryResult<File> create(String studyStr, File entry, QueryOptions options, String sessionId) throws CatalogException {
throw new NotImplementedException("Call to create passing parents and content variables");
}
public QueryResult<File> create(String studyStr, File file, boolean parents, String content, QueryOptions options, String sessionId)
throws CatalogException {
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
return create(study, file, parents, content, options, sessionId);
}
public QueryResult<File> register(Study study, File file, boolean parents, QueryOptions options, String sessionId)
throws CatalogException {
String userId = userManager.getUserId(sessionId);
long studyId = study.getUid();
/** Check and set all the params and create a File object **/
ParamUtils.checkObj(file, "File");
ParamUtils.checkPath(file.getPath(), "path");
file.setType(ParamUtils.defaultObject(file.getType(), File.Type.FILE));
file.setFormat(ParamUtils.defaultObject(file.getFormat(), File.Format.PLAIN));
file.setBioformat(ParamUtils.defaultObject(file.getBioformat(), File.Bioformat.NONE));
file.setDescription(ParamUtils.defaultString(file.getDescription(), ""));
file.setRelatedFiles(ParamUtils.defaultObject(file.getRelatedFiles(), ArrayList::new));
file.setCreationDate(TimeUtils.getTime());
file.setModificationDate(file.getCreationDate());
if (file.getType() == File.Type.FILE) {
file.setStatus(ParamUtils.defaultObject(file.getStatus(), new File.FileStatus(File.FileStatus.STAGE)));
} else {
file.setStatus(ParamUtils.defaultObject(file.getStatus(), new File.FileStatus(File.FileStatus.READY)));
}
if (file.getSize() < 0) {
throw new CatalogException("Error: DiskUsage can't be negative!");
}
// if (file.getExperiment().getId() > 0 && !jobDBAdaptor.experimentExists(file.getExperiment().getId())) {
// throw new CatalogException("Experiment { id: " + file.getExperiment().getId() + "} does not exist.");
// }
file.setSamples(ParamUtils.defaultObject(file.getSamples(), ArrayList::new));
for (Sample sample : file.getSamples()) {
if (sample.getUid() <= 0 || !sampleDBAdaptor.exists(sample.getUid())) {
throw new CatalogException("Sample { id: " + sample.getUid() + "} does not exist.");
}
}
if (file.getJob() != null && file.getJob().getUid() > 0 && !jobDBAdaptor.exists(file.getJob().getUid())) {
throw new CatalogException("Job { id: " + file.getJob().getUid() + "} does not exist.");
}
file.setStats(ParamUtils.defaultObject(file.getStats(), HashMap::new));
file.setAttributes(ParamUtils.defaultObject(file.getAttributes(), HashMap::new));
if (file.getType() == File.Type.DIRECTORY && !file.getPath().endsWith("/")) {
file.setPath(file.getPath() + "/");
}
if (file.getType() == File.Type.FILE && file.getPath().endsWith("/")) {
file.setPath(file.getPath().substring(0, file.getPath().length() - 1));
}
file.setName(Paths.get(file.getPath()).getFileName().toString());
URI uri;
try {
if (file.getType() == File.Type.DIRECTORY) {
uri = getFileUri(studyId, file.getPath(), true);
} else {
uri = getFileUri(studyId, file.getPath(), false);
}
} catch (URISyntaxException e) {
throw new CatalogException(e);
}
file.setUri(uri);
// FIXME: Why am I doing this? Why am I not throwing an exception if it already exists?
// Check if it already exists
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), file.getPath())
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), "!=" + File.FileStatus.TRASHED + ";" + File.FileStatus.DELETED
+ ";" + File.FileStatus.DELETING + ";" + File.FileStatus.PENDING_DELETE + ";" + File.FileStatus.REMOVED);
if (fileDBAdaptor.count(query).first() > 0) {
logger.warn("The file {} already exists in catalog", file.getPath());
}
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.URI.key(), uri)
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), "!=" + File.FileStatus.TRASHED + ";" + File.FileStatus.DELETED
+ ";" + File.FileStatus.DELETING + ";" + File.FileStatus.PENDING_DELETE + ";" + File.FileStatus.REMOVED);
if (fileDBAdaptor.count(query).first() > 0) {
logger.warn("The uri {} of the file is already in catalog but on a different path", uri);
}
boolean external = isExternal(study, file.getPath(), uri);
file.setExternal(external);
file.setRelease(catalogManager.getStudyManager().getCurrentRelease(study, userId));
//Find parent. If parents == true, create folders.
String parentPath = getParentPath(file.getPath());
long parentFileId = fileDBAdaptor.getId(studyId, parentPath);
boolean newParent = false;
if (parentFileId < 0 && StringUtils.isNotEmpty(parentPath)) {
if (parents) {
newParent = true;
File parentFile = new File(File.Type.DIRECTORY, File.Format.NONE, File.Bioformat.NONE, parentPath, "",
new File.FileStatus(File.FileStatus.READY), 0, file.getSamples(), -1, null, Collections.emptyMap(),
Collections.emptyMap());
parentFileId = register(study, parentFile, parents, options, sessionId).first().getUid();
} else {
throw new CatalogDBException("Directory not found " + parentPath);
}
}
//Check permissions
if (parentFileId < 0) {
throw new CatalogException("Unable to create file without a parent file");
} else {
if (!newParent) {
//If parent has been created, for sure we have permissions to create the new file.
authorizationManager.checkFilePermission(studyId, parentFileId, userId, FileAclEntry.FilePermissions.WRITE);
}
}
List<VariableSet> variableSetList = validateNewAnnotationSetsAndExtractVariableSets(study.getUid(), file.getAnnotationSets());
file.setUuid(UUIDUtils.generateOpenCGAUUID(UUIDUtils.Entity.FILE));
checkHooks(file, study.getFqn(), HookConfiguration.Stage.CREATE);
QueryResult<File> queryResult = fileDBAdaptor.insert(studyId, file, variableSetList, options);
// We obtain the permissions set in the parent folder and set them to the file or folder being created
QueryResult<FileAclEntry> allFileAcls = authorizationManager.getAllFileAcls(studyId, parentFileId, userId, false);
// Propagate ACLs
if (allFileAcls.getNumResults() > 0) {
authorizationManager.replicateAcls(studyId, Arrays.asList(queryResult.first().getUid()), allFileAcls.getResult(), Entity.FILE);
}
auditManager.recordCreation(AuditRecord.Resource.file, queryResult.first().getUid(), userId, queryResult.first(), null, null);
matchUpVariantFiles(study.getFqn(), queryResult.getResult(), sessionId);
return queryResult;
}
private QueryResult<File> create(Study study, File file, boolean parents, String content, QueryOptions options, String sessionId)
throws CatalogException {
QueryResult<File> queryResult = register(study, file, parents, options, sessionId);
if (file.getType() == File.Type.FILE && StringUtils.isNotEmpty(content)) {
CatalogIOManager ioManager = catalogIOManagerFactory.getDefault();
// We set parents to true because the file has been successfully registered, which means the directories are already registered
// in catalog
ioManager.createDirectory(Paths.get(file.getUri()).getParent().toUri(), true);
InputStream inputStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
ioManager.createFile(file.getUri(), inputStream);
// Update file parameters
ObjectMap params = new ObjectMap()
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.READY)
.append(FileDBAdaptor.QueryParams.SIZE.key(), ioManager.getFileSize(file.getUri()));
queryResult = fileDBAdaptor.update(file.getUid(), params, QueryOptions.empty());
}
return queryResult;
}
/**
* Upload a file in Catalog.
*
* @param studyStr study where the file will be uploaded.
* @param fileInputStream Input stream of the file to be uploaded.
* @param file File object containing at least the basic metada necessary for a successful upload: path
* @param overwrite Overwrite the current file if any.
* @param parents boolean indicating whether unexisting parent folders should also be created automatically.
* @param sessionId session id of the user performing the upload.
* @return a QueryResult with the file uploaded.
* @throws CatalogException if the user does not have permissions or any other unexpected issue happens.
*/
public QueryResult<File> upload(String studyStr, InputStream fileInputStream, File file, boolean overwrite, boolean parents,
String sessionId) throws CatalogException {
// Check basic parameters
ParamUtils.checkObj(file, "file");
ParamUtils.checkParameter(file.getPath(), FileDBAdaptor.QueryParams.PATH.key());
if (StringUtils.isEmpty(file.getName())) {
file.setName(Paths.get(file.getPath()).toFile().getName());
}
ParamUtils.checkObj(fileInputStream, "file input stream");
QueryResult<Study> studyQueryResult = catalogManager.getStudyManager().get(studyStr,
new QueryOptions(QueryOptions.EXCLUDE, Arrays.asList(StudyDBAdaptor.QueryParams.VARIABLE_SET.key(),
StudyDBAdaptor.QueryParams.ATTRIBUTES.key())), sessionId);
if (studyQueryResult.getNumResults() == 0) {
throw new CatalogException("Study " + studyStr + " not found");
}
Study study = studyQueryResult.first();
QueryResult<File> parentFolders = getParents(false, QueryOptions.empty(), file.getPath(), study.getUid());
if (parentFolders.getNumResults() == 0) {
// There always must be at least the root folder
throw new CatalogException("Unexpected error happened.");
}
String userId = userManager.getUserId(sessionId);
// Check permissions over the most internal path
authorizationManager.checkFilePermission(study.getUid(), parentFolders.first().getUid(), userId,
FileAclEntry.FilePermissions.UPLOAD);
authorizationManager.checkFilePermission(study.getUid(), parentFolders.first().getUid(), userId,
FileAclEntry.FilePermissions.WRITE);
// We obtain the basic studyPath where we will upload the file temporarily
java.nio.file.Path studyPath = Paths.get(study.getUri());
java.nio.file.Path tempFilePath = studyPath.resolve("tmp_" + file.getName()).resolve(file.getName());
logger.info("Uploading file... Temporal file path: {}", tempFilePath.toString());
CatalogIOManager ioManager = catalogManager.getCatalogIOManagerFactory().getDefault();
// Create the temporal directory and upload the file
try {
if (!Files.exists(tempFilePath.getParent())) {
logger.debug("Creating temporal folder: {}", tempFilePath.getParent());
Files.createDirectory(tempFilePath.getParent());
}
// Start uploading the file to the temporal directory
int read;
byte[] bytes = new byte[1024];
// Upload the file to a temporary folder
try (OutputStream out = new FileOutputStream(new java.io.File(tempFilePath.toString()))) {
while ((read = fileInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
}
} catch (Exception e) {
logger.error("Error uploading file {}", file.getName(), e);
// Clean temporal directory
ioManager.deleteDirectory(tempFilePath.getParent().toUri());
throw new CatalogException("Error uploading file " + file.getName(), e);
}
// Register the file in catalog
QueryResult<File> fileQueryResult;
try {
fileQueryResult = catalogManager.getFileManager().register(study, file, parents, QueryOptions.empty(), sessionId);
// Create the directories where the file will be placed (if they weren't created before)
ioManager.createDirectory(Paths.get(fileQueryResult.first().getUri()).getParent().toUri(), true);
new org.opencb.opencga.catalog.managers.FileUtils(catalogManager).upload(tempFilePath.toUri(), fileQueryResult.first(),
null, sessionId, false, overwrite, true, true, Long.MAX_VALUE);
File fileMetadata = new FileMetadataReader(catalogManager)
.setMetadataInformation(fileQueryResult.first(), null, null, sessionId, false);
fileQueryResult.setResult(Collections.singletonList(fileMetadata));
} catch (Exception e) {
logger.error("Error uploading file {}", file.getName(), e);
// Clean temporal directory
ioManager.deleteDirectory(tempFilePath.getParent().toUri());
throw new CatalogException("Error uploading file " + file.getName(), e);
}
// Clean temporal directory
ioManager.deleteDirectory(tempFilePath.getParent().toUri());
return fileQueryResult;
}
/*
* @deprecated This method if broken with multiple studies
*/
@Deprecated
public QueryResult<File> get(Long fileId, QueryOptions options, String sessionId) throws CatalogException {
return get(null, String.valueOf(fileId), options, sessionId);
}
@Override
public QueryResult<File> get(String studyStr, Query query, QueryOptions options, String sessionId) throws CatalogException {
query = ParamUtils.defaultObject(query, Query::new);
options = ParamUtils.defaultObject(options, QueryOptions::new);
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId, new QueryOptions(QueryOptions.INCLUDE,
StudyDBAdaptor.QueryParams.VARIABLE_SET.key()));
query.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
// Fix query if it contains any annotation
AnnotationUtils.fixQueryAnnotationSearch(study, query);
fixQueryObject(study, query, sessionId);
QueryResult<File> fileQueryResult = fileDBAdaptor.get(query, options, userId);
if (fileQueryResult.getNumResults() == 0 && query.containsKey(FileDBAdaptor.QueryParams.UID.key())) {
List<Long> idList = query.getAsLongList(FileDBAdaptor.QueryParams.UID.key());
for (Long myId : idList) {
authorizationManager.checkFilePermission(study.getUid(), myId, userId, FileAclEntry.FilePermissions.VIEW);
}
}
return fileQueryResult;
}
public QueryResult<FileTree> getTree(String fileIdStr, @Nullable String studyStr, Query query, QueryOptions queryOptions, int maxDepth,
String sessionId) throws CatalogException {
long startTime = System.currentTimeMillis();
queryOptions = ParamUtils.defaultObject(queryOptions, QueryOptions::new);
query = ParamUtils.defaultObject(query, Query::new);
if (queryOptions.containsKey(QueryOptions.INCLUDE)) {
// Add type to the queryOptions
List<String> asStringListOld = queryOptions.getAsStringList(QueryOptions.INCLUDE);
List<String> newList = new ArrayList<>(asStringListOld.size());
for (String include : asStringListOld) {
newList.add(include);
}
newList.add(FileDBAdaptor.QueryParams.TYPE.key());
queryOptions.put(QueryOptions.INCLUDE, newList);
} else {
// Avoid excluding type
if (queryOptions.containsKey(QueryOptions.EXCLUDE)) {
List<String> asStringListOld = queryOptions.getAsStringList(QueryOptions.EXCLUDE);
if (asStringListOld.contains(FileDBAdaptor.QueryParams.TYPE.key())) {
// Remove type from exclude options
if (asStringListOld.size() > 1) {
List<String> toExclude = new ArrayList<>(asStringListOld.size() - 1);
for (String s : asStringListOld) {
if (!s.equalsIgnoreCase(FileDBAdaptor.QueryParams.TYPE.key())) {
toExclude.add(s);
}
}
queryOptions.put(QueryOptions.EXCLUDE, StringUtils.join(toExclude.toArray(), ","));
} else {
queryOptions.remove(QueryOptions.EXCLUDE);
}
}
}
}
MyResource<File> resource = getUid(fileIdStr, studyStr, sessionId);
query.put(FileDBAdaptor.QueryParams.STUDY_UID.key(), resource.getStudy().getUid());
// Check if we can obtain the file from the dbAdaptor properly.
QueryOptions qOptions = new QueryOptions()
.append(QueryOptions.INCLUDE, Arrays.asList(FileDBAdaptor.QueryParams.PATH.key(), FileDBAdaptor.QueryParams.NAME.key(),
FileDBAdaptor.QueryParams.UID.key(), FileDBAdaptor.QueryParams.TYPE.key()));
QueryResult<File> fileQueryResult = fileDBAdaptor.get(resource.getResource().getUid(), qOptions);
if (fileQueryResult == null || fileQueryResult.getNumResults() != 1) {
throw new CatalogException("An error occurred with the database.");
}
// Check if the id does not correspond to a directory
if (!fileQueryResult.first().getType().equals(File.Type.DIRECTORY)) {
throw new CatalogException("The file introduced is not a directory.");
}
// Call recursive method
FileTree fileTree = getTree(fileQueryResult.first(), query, queryOptions, maxDepth, resource.getStudy().getUid(),
resource.getUser());
int dbTime = (int) (System.currentTimeMillis() - startTime);
int numResults = countFilesInTree(fileTree);
return new QueryResult<>("File tree", dbTime, numResults, numResults, "", "", Arrays.asList(fileTree));
}
public QueryResult<File> getFilesFromFolder(String folderStr, String studyStr, QueryOptions options, String sessionId)
throws CatalogException {
ParamUtils.checkObj(folderStr, "folder");
MyResource<File> resource = getUid(folderStr, studyStr, sessionId);
options = ParamUtils.defaultObject(options, QueryOptions::new);
if (!resource.getResource().getType().equals(File.Type.DIRECTORY)) {
throw new CatalogDBException("File {path:'" + resource.getResource().getPath() + "'} is not a folder.");
}
Query query = new Query(FileDBAdaptor.QueryParams.DIRECTORY.key(), resource.getResource().getPath());
return get(studyStr, query, options, sessionId);
}
@Override
public DBIterator<File> iterator(String studyStr, Query query, QueryOptions options, String sessionId) throws CatalogException {
query = ParamUtils.defaultObject(query, Query::new);
options = ParamUtils.defaultObject(options, QueryOptions::new);
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
fixQueryObject(study, query, sessionId);
query.put(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
return fileDBAdaptor.iterator(query, options, userId);
}
@Override
public QueryResult<File> search(String studyStr, Query query, QueryOptions options, String sessionId) throws CatalogException {
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId, new QueryOptions(QueryOptions.INCLUDE,
StudyDBAdaptor.QueryParams.VARIABLE_SET.key()));
// Fix query if it contains any annotation
AnnotationUtils.fixQueryAnnotationSearch(study, query);
fixQueryObject(study, query, sessionId);
query.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
QueryResult<File> queryResult = fileDBAdaptor.get(query, options, userId);
return queryResult;
}
void fixQueryObject(Study study, Query query, String sessionId) throws CatalogException {
// The samples introduced could be either ids or names. As so, we should use the smart resolutor to do this.
if (StringUtils.isNotEmpty(query.getString(FileDBAdaptor.QueryParams.SAMPLES.key()))) {
MyResources<Sample> resource = catalogManager.getSampleManager().getUids(
query.getAsStringList(FileDBAdaptor.QueryParams.SAMPLES.key()), study.getFqn(), sessionId);
query.put(FileDBAdaptor.QueryParams.SAMPLE_UIDS.key(), resource.getResourceList().stream().map(Sample::getUid)
.collect(Collectors.toList()));
query.remove(FileDBAdaptor.QueryParams.SAMPLES.key());
}
}
@Override
public QueryResult<File> count(String studyStr, Query query, String sessionId) throws CatalogException {
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId, new QueryOptions(QueryOptions.INCLUDE,
StudyDBAdaptor.QueryParams.VARIABLE_SET.key()));
// Fix query if it contains any annotation
AnnotationUtils.fixQueryAnnotationSearch(study, query);
// The samples introduced could be either ids or names. As so, we should use the smart resolutor to do this.
fixQueryObject(study, query, sessionId);
query.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
QueryResult<Long> queryResultAux = fileDBAdaptor.count(query, userId, StudyAclEntry.StudyPermissions.VIEW_FILES);
return new QueryResult<>("count", queryResultAux.getDbTime(), 0, queryResultAux.first(), queryResultAux.getWarningMsg(),
queryResultAux.getErrorMsg(), Collections.emptyList());
}
@Override
public WriteResult delete(String studyStr, Query query, ObjectMap params, String sessionId) {
Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new));
params = ParamUtils.defaultObject(params, ObjectMap::new);
WriteResult writeResult = new WriteResult("delete", -1, 0, 0, null, null, null);
String userId;
Study study;
StopWatch watch = StopWatch.createStarted();
// If the user is the owner or the admin, we won't check if he has permissions for every single entry
boolean checkPermissions;
// We try to get an iterator containing all the files to be deleted
DBIterator<File> fileIterator;
List<WriteResult.Fail> failedList = new ArrayList<>();
try {
userId = catalogManager.getUserManager().getUserId(sessionId);
study = catalogManager.getStudyManager().resolveId(studyStr, userId, new QueryOptions(QueryOptions.INCLUDE,
StudyDBAdaptor.QueryParams.VARIABLE_SET.key()));
// Fix query if it contains any annotation
AnnotationUtils.fixQueryAnnotationSearch(study, finalQuery);
fixQueryObject(study, finalQuery, sessionId);
finalQuery.append(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
// If the user is the owner or the admin, we won't check if he has permissions for every single entry
checkPermissions = !authorizationManager.checkIsOwnerOrAdmin(study.getUid(), userId);
fileIterator = fileDBAdaptor.iterator(finalQuery, QueryOptions.empty(), userId);
} catch (CatalogException e) {
logger.error("Delete file: {}", e.getMessage(), e);
writeResult.setError(new Error(-1, null, e.getMessage()));
writeResult.setDbTime((int) watch.getTime(TimeUnit.MILLISECONDS));
return writeResult;
}
// We need to avoid processing subfolders or subfiles of an already processed folder independently
Set<String> processedPaths = new HashSet<>();
boolean physicalDelete = params.getBoolean(SKIP_TRASH, false) || params.getBoolean(DELETE_EXTERNAL_FILES, false);
long numMatches = 0;
while (fileIterator.hasNext()) {
File file = fileIterator.next();
if (subpathInPath(file.getPath(), processedPaths)) {
// We skip this folder because it is a subfolder or subfile within an already processed folder
continue;
}
try {
if (checkPermissions) {
authorizationManager.checkFilePermission(study.getUid(), file.getUid(), userId, FileAclEntry.FilePermissions.DELETE);
}
// Check if the file can be deleted
List<File> fileList = checkCanDeleteFile(studyStr, file, physicalDelete, userId);
// Remove job references
MyResources<File> resourceIds = new MyResources<>(userId, study, fileList);
try {
removeJobReferences(resourceIds);
} catch (CatalogException e) {
logger.error("Could not remove job references: {}", e.getMessage(), e);
throw new CatalogException("Could not remove job references: " + e.getMessage(), e);
}
// Remove the index references in case it is a transformed file or folder
try {
updateIndexStatusAfterDeletionOfTransformedFile(study.getUid(), file);
} catch (CatalogException e) {
logger.error("Could not remove relation references: {}", e.getMessage(), e);
throw new CatalogException("Could not remove relation references: " + e.getMessage(), e);
}
if (file.isExternal()) {
// unlink
WriteResult result = unlink(study.getUid(), file);
writeResult.setNumModified(writeResult.getNumModified() + result.getNumModified());
writeResult.setNumMatches(writeResult.getNumMatches() + result.getNumMatches());
} else {
// local
if (physicalDelete) {
// physicalDelete
WriteResult result = physicalDelete(study.getUid(), file, params.getBoolean(FORCE_DELETE, false));
writeResult.setNumModified(writeResult.getNumModified() + result.getNumModified());
writeResult.setNumMatches(writeResult.getNumMatches() + result.getNumMatches());
failedList.addAll(result.getFailed());
} else {
// sendToTrash
WriteResult result = sendToTrash(study.getUid(), file);
writeResult.setNumModified(writeResult.getNumModified() + result.getNumModified());
writeResult.setNumMatches(writeResult.getNumMatches() + result.getNumMatches());
}
}
// We store the processed path as is
if (file.getType() == File.Type.DIRECTORY) {
processedPaths.add(file.getPath());
}
} catch (Exception e) {
numMatches += 1;
failedList.add(new WriteResult.Fail(file.getId(), e.getMessage()));
if (file.getType() == File.Type.FILE) {
logger.debug("Cannot delete file {}: {}", file.getId(), e.getMessage(), e);
} else {
logger.debug("Cannot delete folder {}: {}", file.getId(), e.getMessage(), e);
}
}
}
writeResult.setDbTime((int) watch.getTime(TimeUnit.MILLISECONDS));
writeResult.setFailed(failedList);
writeResult.setNumMatches(writeResult.getNumMatches() + numMatches);
if (!failedList.isEmpty()) {
writeResult.setWarning(Collections.singletonList(new Error(-1, null, "There are files that could not be deleted")));
}
return writeResult;
}
public QueryResult<File> unlink(@Nullable String studyStr, String fileIdStr, String sessionId) throws CatalogException, IOException {
ParamUtils.checkParameter(fileIdStr, "File");
MyResource<File> resource = catalogManager.getFileManager().getUid(fileIdStr, studyStr, sessionId);
String userId = resource.getUser();
long fileId = resource.getResource().getUid();
long studyUid = resource.getStudy().getUid();
// Check 2. User has the proper permissions to delete the file.
authorizationManager.checkFilePermission(studyUid, fileId, userId, FileAclEntry.FilePermissions.DELETE);
// // Check if we can obtain the file from the dbAdaptor properly.
// Query query = new Query()
// .append(FileDBAdaptor.QueryParams.UID.key(), fileId)
// .append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
// .append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), GET_NON_TRASHED_FILES);
// QueryResult<File> fileQueryResult = fileDBAdaptor.get(query, QueryOptions.empty());
// if (fileQueryResult == null || fileQueryResult.getNumResults() != 1) {
// throw new CatalogException("Cannot unlink file '" + fileIdStr + "'. The file was already deleted or unlinked.");
// }
//
// File file = fileQueryResult.first();
File file = resource.getResource();
// Check 3.
if (!file.isExternal()) {
throw new CatalogException("Only previously linked files can be unlinked. Please, use delete instead.");
}
// Check if the file can be deleted
List<File> fileList = checkCanDeleteFile(studyStr, file, false, userId);
// Remove job references
MyResources<File> fileResource = new MyResources<>(userId, resource.getStudy(), fileList);
try {
removeJobReferences(fileResource);
} catch (CatalogException e) {
logger.error("Could not remove job references: {}", e.getMessage(), e);
throw new CatalogException("Could not remove job references: " + e.getMessage(), e);
}
// Remove the index references in case it is a transformed file or folder
try {
updateIndexStatusAfterDeletionOfTransformedFile(studyUid, file);
} catch (CatalogException e) {
logger.error("Could not remove relation references: {}", e.getMessage(), e);
throw new CatalogException("Could not remove relation references: " + e.getMessage(), e);
}
unlink(studyUid, file);
Query query = new Query()
.append(FileDBAdaptor.QueryParams.UID.key(), fileId)
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyUid)
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), Constants.ALL_STATUS);
return fileDBAdaptor.get(query, new QueryOptions(), userId);
}
/**
* This method sets the status of the file to PENDING_DELETE in all cases and does never remove a file from the file system (performed
* by the daemon).
* However, it applies the following changes:
* - Status -> PENDING_DELETE
* - Path -> Renamed to {path}__DELETED_{time}
* - URI -> File or folder name from the file system renamed to {name}__DELETED_{time}
* URI in the database updated accordingly
*
* @param studyId study id.
* @param file file or folder.
* @return a WriteResult object.
*/
private WriteResult physicalDelete(long studyId, File file, boolean forceDelete) throws CatalogException {
StopWatch watch = StopWatch.createStarted();
String currentStatus = file.getStatus().getName();
if (File.FileStatus.DELETED.equals(currentStatus)) {
throw new CatalogException("The file was already deleted");
}
if (File.FileStatus.PENDING_DELETE.equals(currentStatus) && !forceDelete) {
throw new CatalogException("The file was already pending for deletion");
}
if (File.FileStatus.DELETING.equals(currentStatus)) {
throw new CatalogException("The file is already being deleted");
}
URI fileUri = getUri(file);
CatalogIOManager ioManager = catalogIOManagerFactory.get(fileUri);
// Set the path suffix to DELETED
String suffixName = INTERNAL_DELIMITER + File.FileStatus.DELETED + "_" + TimeUtils.getTime();
long numMatched = 0;
long numModified = 0;
List<WriteResult.Fail> failedList = new ArrayList<>();
if (file.getType() == File.Type.FILE) {
logger.debug("Deleting physical file {}" + file.getPath());
numMatched += 1;
try {
// 1. Set the file status to deleting
ObjectMap update = new ObjectMap()
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.DELETING)
.append(FileDBAdaptor.QueryParams.PATH.key(), file.getPath() + suffixName);
fileDBAdaptor.update(file.getUid(), update, QueryOptions.empty());
// 2. Delete the file from disk
try {
Files.delete(Paths.get(fileUri));
} catch (IOException e) {
logger.error("{}", e.getMessage(), e);
// We rollback and leave the file/folder in PENDING_DELETE status
update = new ObjectMap(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.PENDING_DELETE);
fileDBAdaptor.update(file.getUid(), update, QueryOptions.empty());
throw new CatalogException("Could not delete physical file/folder: " + e.getMessage(), e);
}
// 3. Update the file status in the database. Set to delete
update = new ObjectMap(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.DELETED);
fileDBAdaptor.update(file.getUid(), update, QueryOptions.empty());
numModified += 1;
} catch (CatalogException e) {
failedList.add(new WriteResult.Fail(file.getId(), e.getMessage()));
}
} else {
logger.debug("Starting physical deletion of folder {}", file.getId());
// Rename the directory in the filesystem.
URI newURI;
String basePath = Paths.get(file.getPath()).toString();
String suffixedPath;
if (!File.FileStatus.PENDING_DELETE.equals(currentStatus)) {
try {
newURI = UriUtils.createDirectoryUri(Paths.get(fileUri).toString() + suffixName);
} catch (URISyntaxException e) {
logger.error("URI exception: {}", e.getMessage(), e);
throw new CatalogException("URI exception: " + e.getMessage(), e);
}
logger.debug("Renaming {} to {}", fileUri.toString(), newURI.toString());
ioManager.rename(fileUri, newURI);
suffixedPath = basePath + suffixName;
} else {
// newURI is actually = to fileURI
newURI = fileUri;
// suffixedPath = basePath
suffixedPath = basePath;
}
// Obtain all files and folders within the folder
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + file.getPath() + "*")
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), GET_NON_DELETED_FILES);
logger.debug("Looking for files and folders inside {} to mark as {}", file.getPath(), forceDelete
? File.FileStatus.DELETED : File.FileStatus.PENDING_DELETE);
QueryOptions options = new QueryOptions();
if (forceDelete) {
options.append(QueryOptions.SORT, FileDBAdaptor.QueryParams.PATH.key())
.append(QueryOptions.ORDER, QueryOptions.DESCENDING);
}
DBIterator<File> iterator = fileDBAdaptor.iterator(query, options);
while (iterator.hasNext()) {
File auxFile = iterator.next();
numMatched += 1;
String newPath;
String newUri;
if (!File.FileStatus.PENDING_DELETE.equals(currentStatus)) {
// Edit the PATH
newPath = auxFile.getPath().replaceFirst(basePath, suffixedPath);
newUri = auxFile.getUri().toString().replaceFirst(fileUri.toString(), newURI.toString());
} else {
newPath = auxFile.getPath();
newUri = auxFile.getUri().toString();
}
try {
if (!forceDelete) {
// Deferred deletion
logger.debug("Replacing old uri {} for {}, old path {} for {}, and setting the status to {}",
auxFile.getUri().toString(), newUri, auxFile.getPath(), newPath, File.FileStatus.PENDING_DELETE);
ObjectMap updateParams = new ObjectMap()
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.PENDING_DELETE)
.append(FileDBAdaptor.QueryParams.URI.key(), newUri)
.append(FileDBAdaptor.QueryParams.PATH.key(), newPath);
fileDBAdaptor.update(auxFile.getUid(), updateParams, QueryOptions.empty());
} else {
// We delete the files and folders now
// 1. Set the file status to deleting
ObjectMap update = new ObjectMap()
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.DELETING)
.append(FileDBAdaptor.QueryParams.URI.key(), newUri)
.append(FileDBAdaptor.QueryParams.PATH.key(), newPath);
fileDBAdaptor.update(auxFile.getUid(), update, QueryOptions.empty());
// 2. Delete the file from disk
try {
Files.delete(Paths.get(newUri.replaceFirst("file://", "")));
} catch (IOException e) {
logger.error("{}", e.getMessage(), e);
// We rollback and leave the file/folder in PENDING_DELETE status
update = new ObjectMap(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.PENDING_DELETE);
fileDBAdaptor.update(auxFile.getUid(), update, QueryOptions.empty());
throw new CatalogException("Could not delete physical file/folder: " + e.getMessage(), e);
}
// 3. Update the file status in the database. Set to delete
update = new ObjectMap(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.DELETED);
fileDBAdaptor.update(auxFile.getUid(), update, QueryOptions.empty());
}
numModified += 1;
} catch (CatalogException e) {
failedList.add(new WriteResult.Fail(auxFile.getId(), e.getMessage()));
}
}
}
return new WriteResult("delete", (int) watch.getTime(TimeUnit.MILLISECONDS), numMatched, numModified, failedList, null, null);
}
private WriteResult sendToTrash(long studyId, File file) throws CatalogDBException {
// It doesn't really matter if file is a file or a directory. I can directly set the status of the file or the directory +
// subfiles and subdirectories doing a single query as I don't need to rename anything
// Obtain all files within the folder
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + file.getPath() + "*")
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), GET_NON_DELETED_FILES);
ObjectMap params = new ObjectMap()
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.TRASHED);
QueryResult<Long> update = fileDBAdaptor.update(query, params, QueryOptions.empty());
return new WriteResult("trash", update.getDbTime(), update.first(), update.first(), null, null, null);
}
private WriteResult unlink(long studyId, File file) throws CatalogDBException {
StopWatch watch = StopWatch.createStarted();
String suffixName = INTERNAL_DELIMITER + File.FileStatus.REMOVED + "_" + TimeUtils.getTime();
// Set the new path
String basePath = Paths.get(file.getPath()).toString();
String suffixedPath = basePath + suffixName;
long numMatched = 0;
long numModified = 0;
if (file.getType() == File.Type.FILE) {
numMatched += 1;
ObjectMap params = new ObjectMap()
.append(FileDBAdaptor.QueryParams.PATH.key(), file.getPath().replaceFirst(basePath, suffixedPath))
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.REMOVED);
logger.debug("Unlinking file {}", file.getPath());
fileDBAdaptor.update(file.getUid(), params, QueryOptions.empty());
numModified += 1;
} else {
// Obtain all files within the folder
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + file.getPath() + "*")
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), GET_NON_DELETED_FILES);
logger.debug("Looking for files and folders inside {} to unlink", file.getPath());
DBIterator<File> iterator = fileDBAdaptor.iterator(query, new QueryOptions());
while (iterator.hasNext()) {
File auxFile = iterator.next();
numMatched += 1;
ObjectMap updateParams = new ObjectMap()
.append(FileDBAdaptor.QueryParams.PATH.key(), auxFile.getPath().replaceFirst(basePath, suffixedPath))
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), File.FileStatus.REMOVED);
fileDBAdaptor.update(auxFile.getUid(), updateParams, QueryOptions.empty());
numModified += 1;
}
}
return new WriteResult("unlink", (int) watch.getTime(TimeUnit.MILLISECONDS), numMatched, numModified, null, null, null);
}
private boolean subpathInPath(String subpath, Set<String> pathSet) {
String[] split = StringUtils.split(subpath, "/");
String auxPath = "";
for (String s : split) {
auxPath += s + "/";
if (pathSet.contains(auxPath)) {
return true;
}
}
return false;
}
public QueryResult<File> updateAnnotations(String studyStr, String fileStr, String annotationSetId,
Map<String, Object> annotations, ParamUtils.CompleteUpdateAction action,
QueryOptions options, String token) throws CatalogException {
if (annotations == null || annotations.isEmpty()) {
return new QueryResult<>(fileStr, -1, -1, -1, "Nothing to do: The map of annotations is empty", "", Collections.emptyList());
}
ObjectMap params = new ObjectMap(AnnotationSetManager.ANNOTATIONS, new AnnotationSet(annotationSetId, "", annotations));
options = ParamUtils.defaultObject(options, QueryOptions::new);
options.put(Constants.ACTIONS, new ObjectMap(AnnotationSetManager.ANNOTATIONS, action));
return update(studyStr, fileStr, params, options, token);
}
public QueryResult<File> removeAnnotations(String studyStr, String fileStr, String annotationSetId,
List<String> annotations, QueryOptions options, String token) throws CatalogException {
return updateAnnotations(studyStr, fileStr, annotationSetId, new ObjectMap("remove", StringUtils.join(annotations, ",")),
ParamUtils.CompleteUpdateAction.REMOVE, options, token);
}
public QueryResult<File> resetAnnotations(String studyStr, String fileStr, String annotationSetId, List<String> annotations,
QueryOptions options, String token) throws CatalogException {
return updateAnnotations(studyStr, fileStr, annotationSetId, new ObjectMap("reset", StringUtils.join(annotations, ",")),
ParamUtils.CompleteUpdateAction.RESET, options, token);
}
@Override
public QueryResult<File> update(String studyStr, String entryStr, ObjectMap parameters, QueryOptions options, String sessionId)
throws CatalogException {
ParamUtils.checkObj(parameters, "Parameters");
options = ParamUtils.defaultObject(options, QueryOptions::new);
MyResource<File> resource = getUid(entryStr, studyStr, sessionId);
String userId = userManager.getUserId(sessionId);
File file = resource.getResource();
// Check permissions...
// Only check write annotation permissions if the user wants to update the annotation sets
if (parameters.containsKey(FileDBAdaptor.QueryParams.ANNOTATION_SETS.key())) {
authorizationManager.checkFilePermission(resource.getStudy().getUid(), resource.getResource().getUid(), resource.getUser(),
FileAclEntry.FilePermissions.WRITE_ANNOTATIONS);
}
// Only check update permissions if the user wants to update anything apart from the annotation sets
if ((parameters.size() == 1 && !parameters.containsKey(FileDBAdaptor.QueryParams.ANNOTATION_SETS.key()))
|| parameters.size() > 1) {
authorizationManager.checkFilePermission(resource.getStudy().getUid(), file.getUid(), userId,
FileAclEntry.FilePermissions.WRITE);
}
try {
ParamUtils.checkAllParametersExist(parameters.keySet().iterator(), (a) -> FileDBAdaptor.UpdateParams.getParam(a) != null);
} catch (CatalogParameterException e) {
throw new CatalogException("Could not update: " + e.getMessage(), e);
}
// We obtain the numeric ids of the samples given
if (StringUtils.isNotEmpty(parameters.getString(FileDBAdaptor.QueryParams.SAMPLES.key()))) {
List<String> sampleIdStr = parameters.getAsStringList(FileDBAdaptor.QueryParams.SAMPLES.key());
MyResources<Sample> sampleResource = catalogManager.getSampleManager().getUids(sampleIdStr, studyStr, sessionId);
// Avoid sample duplicates
Set<Long> sampleIdsSet = sampleResource.getResourceList().stream().map(Sample::getUid).collect(Collectors.toSet());
List<Sample> sampleList = new ArrayList<>(sampleIdsSet.size());
for (Long sampleId : sampleIdsSet) {
Sample sample = new Sample();
sample.setUid(sampleId);
sampleList.add(sample);
}
parameters.put(FileDBAdaptor.QueryParams.SAMPLES.key(), sampleList);
}
//Name must be changed with "rename".
if (parameters.containsKey(FileDBAdaptor.QueryParams.NAME.key())) {
logger.info("Rename file using update method!");
rename(studyStr, file.getPath(), parameters.getString(FileDBAdaptor.QueryParams.NAME.key()), sessionId);
}
return unsafeUpdate(resource.getStudy(), file, parameters, options, userId);
}
QueryResult<File> unsafeUpdate(Study study, File file, ObjectMap parameters, QueryOptions options, String userId)
throws CatalogException {
if (isRootFolder(file)) {
throw new CatalogException("Cannot modify root folder");
}
try {
ParamUtils.checkAllParametersExist(parameters.keySet().iterator(), (a) -> FileDBAdaptor.UpdateParams.getParam(a) != null);
} catch (CatalogParameterException e) {
throw new CatalogException("Could not update: " + e.getMessage(), e);
}
MyResource<File> resource = new MyResource<>(userId, study, file);
List<VariableSet> variableSetList = checkUpdateAnnotationsAndExtractVariableSets(resource, parameters, options, fileDBAdaptor);
String ownerId = studyDBAdaptor.getOwnerId(study.getUid());
fileDBAdaptor.update(file.getUid(), parameters, variableSetList, options);
QueryResult<File> queryResult = fileDBAdaptor.get(file.getUid(), options);
auditManager.recordUpdate(AuditRecord.Resource.file, file.getUid(), userId, parameters, null, null);
userDBAdaptor.updateUserLastModified(ownerId);
return queryResult;
}
private void removeJobReferences(MyResources<File> resource) throws CatalogException {
QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(
JobDBAdaptor.QueryParams.UID.key(), JobDBAdaptor.QueryParams.INPUT.key(), JobDBAdaptor.QueryParams.OUTPUT.key(),
JobDBAdaptor.QueryParams.OUT_DIR.key(), JobDBAdaptor.QueryParams.ATTRIBUTES.key()));
List<Long> resourceList = resource.getResourceList().stream().map(File::getUid).collect(Collectors.toList());
// Find all the jobs containing references to any of the files to be deleted
Query query = new Query()
.append(JobDBAdaptor.QueryParams.STUDY_UID.key(), resource.getStudy().getUid())
.append(JobDBAdaptor.QueryParams.INPUT_UID.key(), resourceList)
.append(JobDBAdaptor.QueryParams.STATUS_NAME.key(), Constants.ALL_STATUS);
QueryResult<Job> jobInputFiles = jobDBAdaptor.get(query, options);
query = new Query()
.append(JobDBAdaptor.QueryParams.STUDY_UID.key(), resource.getStudy().getUid())
.append(JobDBAdaptor.QueryParams.OUTPUT_UID.key(), resourceList)
.append(JobDBAdaptor.QueryParams.STATUS_NAME.key(), Constants.ALL_STATUS);
QueryResult<Job> jobOutputFiles = jobDBAdaptor.get(query, options);
query = new Query()
.append(JobDBAdaptor.QueryParams.STUDY_UID.key(), resource.getStudy().getUid())
.append(JobDBAdaptor.QueryParams.OUT_DIR_UID.key(), resourceList)
.append(JobDBAdaptor.QueryParams.STATUS_NAME.key(), Constants.ALL_STATUS);
QueryResult<Job> jobOutDirFolders = jobDBAdaptor.get(query, options);
// We create a job map that will contain all the changes done so far to avoid performing more queries
Map<Long, Job> jobMap = new HashMap<>();
Set<Long> fileIdsReferencedInJobs = new HashSet<>();
for (Job job : jobInputFiles.getResult()) {
fileIdsReferencedInJobs.addAll(job.getInput().stream().map(File::getUid).collect(Collectors.toList()));
jobMap.put(job.getUid(), job);
}
for (Job job : jobOutputFiles.getResult()) {
fileIdsReferencedInJobs.addAll(job.getOutput().stream().map(File::getUid).collect(Collectors.toList()));
jobMap.put(job.getUid(), job);
}
for (Job job : jobOutDirFolders.getResult()) {
fileIdsReferencedInJobs.add(job.getOutDir().getUid());
jobMap.put(job.getUid(), job);
}
if (fileIdsReferencedInJobs.isEmpty()) {
logger.info("No associated jobs found for the files to be deleted.");
return;
}
// We create a map with the files that are related to jobs that are going to be deleted
Map<Long, File> relatedFileMap = new HashMap<>();
for (Long fileId : resourceList) {
if (fileIdsReferencedInJobs.contains(fileId)) {
relatedFileMap.put(fileId, null);
}
}
if (relatedFileMap.isEmpty()) {
logger.error("Unexpected error: None of the matching jobs seem to be related to any of the files to be deleted");
throw new CatalogException("Internal error. Please, report to the OpenCGA administrators.");
}
// We obtain the current information of those files
query = new Query()
.append(FileDBAdaptor.QueryParams.UID.key(), relatedFileMap.keySet())
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), resource.getStudy().getUid())
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), GET_NON_DELETED_FILES);
QueryResult<File> fileQueryResult = fileDBAdaptor.get(query, QueryOptions.empty());
if (fileQueryResult.getNumResults() < relatedFileMap.size()) {
logger.error("Unexpected error: The number of files fetched does not match the number of files looked for.");
throw new CatalogException("Internal error. Please, report to the OpenCGA administrators.");
}
relatedFileMap = new HashMap<>();
for (File file : fileQueryResult.getResult()) {
relatedFileMap.put(file.getUid(), file);
}
// We update the input files from the jobs
for (Job jobAux : jobInputFiles.getResult()) {
Job job = jobMap.get(jobAux.getUid());
List<File> inputFiles = new ArrayList<>(job.getInput().size());
List<File> attributeFiles = new ArrayList<>(job.getInput().size());
for (File file : job.getInput()) {
if (relatedFileMap.containsKey(file.getUid())) {
attributeFiles.add(relatedFileMap.get(file.getUid()));
} else {
inputFiles.add(file);
}
}
if (attributeFiles.isEmpty()) {
logger.error("Unexpected error: Deleted file was apparently not found in the map of job associated files");
throw new CatalogException("Internal error. Please, report to the OpenCGA administrators.");
}
Map<String, Object> attributes = job.getAttributes();
ObjectMap opencgaAttributes;
if (!attributes.containsKey(Constants.PRIVATE_OPENCGA_ATTRIBUTES)) {
opencgaAttributes = new ObjectMap();
attributes.put(Constants.PRIVATE_OPENCGA_ATTRIBUTES, opencgaAttributes);
} else {
opencgaAttributes = (ObjectMap) attributes.get(Constants.PRIVATE_OPENCGA_ATTRIBUTES);
}
List<Object> fileList = opencgaAttributes.getAsList(Constants.JOB_DELETED_INPUT_FILES);
if (fileList == null || fileList.isEmpty()) {
fileList = new ArrayList<>(attributeFiles);
} else {
fileList = new ArrayList<>(fileList);
fileList.addAll(attributeFiles);
}
opencgaAttributes.put(Constants.JOB_DELETED_INPUT_FILES, fileList);
ObjectMap params = new ObjectMap()
.append(JobDBAdaptor.QueryParams.ATTRIBUTES.key(), attributes)
.append(JobDBAdaptor.QueryParams.INPUT.key(), inputFiles);
jobDBAdaptor.update(job.getUid(), params, QueryOptions.empty());
}
// We update the output files from the jobs
for (Job jobAux : jobOutputFiles.getResult()) {
Job job = jobMap.get(jobAux.getUid());
List<File> outputFiles = new ArrayList<>(job.getOutput().size());
List<File> attributeFiles = new ArrayList<>(job.getOutput().size());
for (File file : job.getOutput()) {
if (relatedFileMap.containsKey(file.getUid())) {
attributeFiles.add(relatedFileMap.get(file.getUid()));
} else {
outputFiles.add(file);
}
}
if (attributeFiles.isEmpty()) {
logger.error("Unexpected error: Deleted file was apparently not found in the map of job associated files");
throw new CatalogException("Internal error. Please, report to the OpenCGA administrators.");
}
Map<String, Object> attributes = job.getAttributes();
ObjectMap opencgaAttributes;
if (!attributes.containsKey(Constants.PRIVATE_OPENCGA_ATTRIBUTES)) {
opencgaAttributes = new ObjectMap();
attributes.put(Constants.PRIVATE_OPENCGA_ATTRIBUTES, opencgaAttributes);
} else {
opencgaAttributes = (ObjectMap) attributes.get(Constants.PRIVATE_OPENCGA_ATTRIBUTES);
}
List<Object> fileList = opencgaAttributes.getAsList(Constants.JOB_DELETED_OUTPUT_FILES);
if (fileList == null || fileList.isEmpty()) {
fileList = new ArrayList<>(attributeFiles);
} else {
fileList = new ArrayList<>(fileList);
fileList.addAll(attributeFiles);
}
opencgaAttributes.put(Constants.JOB_DELETED_OUTPUT_FILES, fileList);
ObjectMap params = new ObjectMap()
.append(JobDBAdaptor.QueryParams.ATTRIBUTES.key(), attributes)
.append(JobDBAdaptor.QueryParams.OUTPUT.key(), outputFiles);
jobDBAdaptor.update(job.getUid(), params, QueryOptions.empty());
}
// We update the outdir file from the jobs
for (Job jobAux : jobOutDirFolders.getResult()) {
Job job = jobMap.get(jobAux.getUid());
File outDir = job.getOutDir();
if (outDir == null || outDir.getUid() <= 0) {
logger.error("Unexpected error: Output directory from job not found?");
throw new CatalogException("Internal error. Please, report to the OpenCGA administrators.");
}
if (!relatedFileMap.containsKey(job.getOutDir().getUid())) {
logger.error("Unexpected error: Deleted output directory was apparently not found in the map of job associated files");
throw new CatalogException("Internal error. Please, report to the OpenCGA administrators.");
}
// We get the whole file entry
outDir = relatedFileMap.get(outDir.getUid());
Map<String, Object> attributes = job.getAttributes();
ObjectMap opencgaAttributes;
if (!attributes.containsKey(Constants.PRIVATE_OPENCGA_ATTRIBUTES)) {
opencgaAttributes = new ObjectMap();
attributes.put(Constants.PRIVATE_OPENCGA_ATTRIBUTES, opencgaAttributes);
} else {
opencgaAttributes = (ObjectMap) attributes.get(Constants.PRIVATE_OPENCGA_ATTRIBUTES);
}
opencgaAttributes.put(Constants.JOB_DELETED_OUTPUT_DIRECTORY, outDir);
ObjectMap params = new ObjectMap()
.append(JobDBAdaptor.QueryParams.ATTRIBUTES.key(), attributes)
.append(JobDBAdaptor.QueryParams.OUT_DIR.key(), -1L);
jobDBAdaptor.update(job.getUid(), params, QueryOptions.empty());
}
}
public QueryResult<File> link(String studyStr, URI uriOrigin, String pathDestiny, ObjectMap params, String sessionId)
throws CatalogException, IOException {
// We make two attempts to link to ensure the behaviour remains even if it is being called at the same time link from different
// threads
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
try {
return privateLink(study, uriOrigin, pathDestiny, params, sessionId);
} catch (CatalogException | IOException e) {
return privateLink(study, uriOrigin, pathDestiny, params, sessionId);
}
}
@Override
public QueryResult rank(String studyStr, Query query, String field, int numResults, boolean asc, String sessionId)
throws CatalogException {
query = ParamUtils.defaultObject(query, Query::new);
ParamUtils.checkObj(field, "field");
ParamUtils.checkObj(sessionId, "sessionId");
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
authorizationManager.checkStudyPermission(study.getUid(), userId, StudyAclEntry.StudyPermissions.VIEW_FILES);
// TODO: In next release, we will have to check the count parameter from the queryOptions object.
boolean count = true;
query.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
QueryResult queryResult = null;
if (count) {
// We do not need to check for permissions when we show the count of files
queryResult = fileDBAdaptor.rank(query, field, numResults, asc);
}
return ParamUtils.defaultObject(queryResult, QueryResult::new);
}
@Override
public QueryResult groupBy(@Nullable String studyStr, Query query, List<String> fields, QueryOptions options, String sessionId)
throws CatalogException {
query = ParamUtils.defaultObject(query, Query::new);
options = ParamUtils.defaultObject(options, QueryOptions::new);
if (fields == null || fields.size() == 0) {
throw new CatalogException("Empty fields parameter.");
}
String userId = userManager.getUserId(sessionId);
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
fixQueryObject(study, query, sessionId);
// Add study id to the query
query.put(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid());
// We do not need to check for permissions when we show the count of files
QueryResult queryResult = fileDBAdaptor.groupBy(query, fields, options, userId);
return ParamUtils.defaultObject(queryResult, QueryResult::new);
}
public QueryResult<File> rename(String studyStr, String fileStr, String newName, String sessionId) throws CatalogException {
ParamUtils.checkFileName(newName, "name");
MyResource<File> resource = getUid(fileStr, studyStr, sessionId);
String userId = resource.getUser();
Study study = resource.getStudy();
String ownerId = StringUtils.split(study.getFqn(), "@")[0];
File file = resource.getResource();
authorizationManager.checkFilePermission(study.getUid(), file.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
if (file.getName().equals(newName)) {
return new QueryResult<>("rename", -1, 0, 0, "The file was already named " + newName, "", Collections.emptyList());
}
if (isRootFolder(file)) {
throw new CatalogException("Can not rename root folder");
}
String oldPath = file.getPath();
Path parent = Paths.get(oldPath).getParent();
String newPath;
if (parent == null) {
newPath = newName;
} else {
newPath = parent.resolve(newName).toString();
}
userDBAdaptor.updateUserLastModified(ownerId);
CatalogIOManager catalogIOManager;
URI oldUri = file.getUri();
URI newUri = Paths.get(oldUri).getParent().resolve(newName).toUri();
// URI studyUri = file.getUri();
boolean isExternal = file.isExternal(); //If the file URI is not null, the file is external located.
QueryResult<File> result;
switch (file.getType()) {
case DIRECTORY:
if (!isExternal) { //Only rename non external files
catalogIOManager = catalogIOManagerFactory.get(oldUri); // TODO? check if something in the subtree is not READY?
if (catalogIOManager.exists(oldUri)) {
catalogIOManager.rename(oldUri, newUri); // io.move() 1
}
}
result = fileDBAdaptor.rename(file.getUid(), newPath, newUri.toString(), null);
auditManager.recordUpdate(AuditRecord.Resource.file, file.getUid(), userId, new ObjectMap("path", newPath)
.append("name", newName), "rename", null);
break;
case FILE:
if (!isExternal) { //Only rename non external files
catalogIOManager = catalogIOManagerFactory.get(oldUri);
catalogIOManager.rename(oldUri, newUri);
}
result = fileDBAdaptor.rename(file.getUid(), newPath, newUri.toString(), null);
auditManager.recordUpdate(AuditRecord.Resource.file, file.getUid(), userId, new ObjectMap("path", newPath)
.append("name", newName), "rename", null);
break;
default:
throw new CatalogException("Unknown file type " + file.getType());
}
return result;
}
public DataInputStream grep(String studyStr, String fileStr, String pattern, QueryOptions options, String sessionId)
throws CatalogException {
MyResource<File> resource = getUid(fileStr, studyStr, sessionId);
authorizationManager.checkFilePermission(resource.getStudy().getUid(), resource.getResource().getUid(), resource.getUser(),
FileAclEntry.FilePermissions.VIEW);
URI fileUri = getUri(resource.getResource());
boolean ignoreCase = options.getBoolean("ignoreCase");
boolean multi = options.getBoolean("multi");
return catalogIOManagerFactory.get(fileUri).getGrepFileObject(fileUri, pattern, ignoreCase, multi);
}
public DataInputStream download(String studyStr, String fileStr, int start, int limit, QueryOptions options, String sessionId)
throws CatalogException {
MyResource<File> resource = getUid(fileStr, studyStr, sessionId);
authorizationManager.checkFilePermission(resource.getStudy().getUid(), resource.getResource().getUid(), resource.getUser(),
FileAclEntry.FilePermissions.DOWNLOAD);
URI fileUri = getUri(resource.getResource());
return catalogIOManagerFactory.get(fileUri).getFileObject(fileUri, start, limit);
}
public QueryResult<Job> index(String studyStr, List<String> fileList, String type, Map<String, String> params, String sessionId)
throws CatalogException {
params = ParamUtils.defaultObject(params, HashMap::new);
MyResources<File> resource = getUids(fileList, studyStr, sessionId);
List<File> fileFolderIdList = resource.getResourceList();
long studyId = resource.getStudy().getUid();
String userId = resource.getUser();
// Define the output directory where the indexes will be put
String outDirPath = ParamUtils.defaultString(params.get("outdir"), "/");
if (outDirPath != null && outDirPath.contains("/") && !outDirPath.endsWith("/")) {
outDirPath = outDirPath + "/";
}
File outDir;
try {
outDir = smartResolutor(resource.getStudy().getUid(), outDirPath, resource.getUser());
} catch (CatalogException e) {
logger.warn("'{}' does not exist. Trying to create the output directory.", outDirPath);
QueryResult<File> folder = createFolder(studyStr, outDirPath, new File.FileStatus(), true, "", new QueryOptions(), sessionId);
outDir = folder.first();
}
authorizationManager.checkFilePermission(studyId, outDir.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
QueryResult<Job> jobQueryResult;
List<File> fileIdList = new ArrayList<>();
String indexDaemonType = null;
String jobName = null;
String description = null;
QueryOptions queryOptions = new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(
FileDBAdaptor.QueryParams.NAME.key(),
FileDBAdaptor.QueryParams.PATH.key(),
FileDBAdaptor.QueryParams.URI.key(),
FileDBAdaptor.QueryParams.TYPE.key(),
FileDBAdaptor.QueryParams.BIOFORMAT.key(),
FileDBAdaptor.QueryParams.FORMAT.key(),
FileDBAdaptor.QueryParams.INDEX.key())
);
if (type.equals("VCF")) {
indexDaemonType = IndexDaemon.VARIANT_TYPE;
Boolean transform = Boolean.valueOf(params.get("transform"));
Boolean load = Boolean.valueOf(params.get("load"));
if (transform && !load) {
jobName = "variant_transform";
description = "Transform variants from " + fileList;
} else if (load && !transform) {
description = "Load variants from " + fileList;
jobName = "variant_load";
} else {
description = "Index variants from " + fileList;
jobName = "variant_index";
}
for (File file : fileFolderIdList) {
if (File.Type.DIRECTORY.equals(file.getType())) {
// Retrieve all the VCF files that can be found within the directory
String path = file.getPath().endsWith("/") ? file.getPath() : file.getPath() + "/";
Query query = new Query()
.append(FileDBAdaptor.QueryParams.FORMAT.key(), Arrays.asList(File.Format.VCF, File.Format.GVCF))
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + path + "*")
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId);
QueryResult<File> fileQueryResult = fileDBAdaptor.get(query, queryOptions);
if (fileQueryResult.getNumResults() == 0) {
throw new CatalogException("No VCF files could be found in directory " + file.getPath());
}
for (File fileTmp : fileQueryResult.getResult()) {
authorizationManager.checkFilePermission(studyId, fileTmp.getUid(), userId, FileAclEntry.FilePermissions.VIEW);
authorizationManager.checkFilePermission(studyId, fileTmp.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
fileIdList.add(fileTmp);
}
} else {
if (isTransformedFile(file.getName())) {
if (file.getRelatedFiles() == null || file.getRelatedFiles().isEmpty()) {
catalogManager.getFileManager().matchUpVariantFiles(studyStr, Collections.singletonList(file), sessionId);
}
if (file.getRelatedFiles() != null) {
for (File.RelatedFile relatedFile : file.getRelatedFiles()) {
if (File.RelatedFile.Relation.PRODUCED_FROM.equals(relatedFile.getRelation())) {
Query query = new Query(FileDBAdaptor.QueryParams.UID.key(), relatedFile.getFileId());
file = get(studyStr, query, null, sessionId).first();
break;
}
}
}
}
if (!File.Format.VCF.equals(file.getFormat()) && !File.Format.GVCF.equals(file.getFormat())) {
throw new CatalogException("The file " + file.getName() + " is not a VCF file.");
}
authorizationManager.checkFilePermission(studyId, file.getUid(), userId, FileAclEntry.FilePermissions.VIEW);
authorizationManager.checkFilePermission(studyId, file.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
fileIdList.add(file);
}
}
if (fileIdList.size() == 0) {
throw new CatalogException("Cannot send to index. No files could be found to be indexed.");
}
params.put("outdir", outDir.getId());
params.put("sid", sessionId);
} else if (type.equals("BAM")) {
indexDaemonType = IndexDaemon.ALIGNMENT_TYPE;
jobName = "AlignmentIndex";
for (File file : fileFolderIdList) {
if (File.Type.DIRECTORY.equals(file.getType())) {
// Retrieve all the BAM files that can be found within the directory
String path = file.getPath().endsWith("/") ? file.getPath() : file.getPath() + "/";
Query query = new Query(FileDBAdaptor.QueryParams.FORMAT.key(), Arrays.asList(File.Format.SAM, File.Format.BAM))
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + path + "*")
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId);
QueryResult<File> fileQueryResult = fileDBAdaptor.get(query, queryOptions);
if (fileQueryResult.getNumResults() == 0) {
throw new CatalogException("No SAM/BAM files could be found in directory " + file.getPath());
}
for (File fileTmp : fileQueryResult.getResult()) {
authorizationManager.checkFilePermission(studyId, fileTmp.getUid(), userId, FileAclEntry.FilePermissions.VIEW);
authorizationManager.checkFilePermission(studyId, fileTmp.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
fileIdList.add(fileTmp);
}
} else {
if (!File.Format.BAM.equals(file.getFormat()) && !File.Format.SAM.equals(file.getFormat())) {
throw new CatalogException("The file " + file.getName() + " is not a SAM/BAM file.");
}
authorizationManager.checkFilePermission(studyId, file.getUid(), userId, FileAclEntry.FilePermissions.VIEW);
authorizationManager.checkFilePermission(studyId, file.getUid(), userId, FileAclEntry.FilePermissions.WRITE);
fileIdList.add(file);
}
}
}
if (fileIdList.size() == 0) {
throw new CatalogException("Cannot send to index. No files could be found to be indexed.");
}
String fileIds = fileIdList.stream().map(File::getId).collect(Collectors.joining(","));
params.put("file", fileIds);
List<File> outputList = outDir.getUid() > 0 ? Arrays.asList(outDir) : Collections.emptyList();
ObjectMap attributes = new ObjectMap();
attributes.put(IndexDaemon.INDEX_TYPE, indexDaemonType);
attributes.putIfNotNull(Job.OPENCGA_OUTPUT_DIR, outDirPath);
attributes.putIfNotNull(Job.OPENCGA_STUDY, resource.getStudy().getFqn());
logger.info("job description: " + description);
jobQueryResult = catalogManager.getJobManager().queue(studyStr, jobName, description, "opencga-analysis.sh",
Job.Type.INDEX, params, fileIdList, outputList, outDir, attributes, sessionId);
jobQueryResult.first().setToolId(jobName);
return jobQueryResult;
}
public void setFileIndex(String studyStr, String fileId, FileIndex index, String sessionId) throws CatalogException {
MyResource<File> resource = getUid(fileId, studyStr, sessionId);
authorizationManager.checkFilePermission(resource.getStudy().getUid(), resource.getResource().getUid(), resource.getUser(),
FileAclEntry.FilePermissions.WRITE);
ObjectMap parameters = new ObjectMap(FileDBAdaptor.QueryParams.INDEX.key(), index);
fileDBAdaptor.update(resource.getResource().getUid(), parameters, QueryOptions.empty());
auditManager.recordUpdate(AuditRecord.Resource.file, resource.getResource().getUid(), resource.getUser(), parameters, null, null);
}
public void setDiskUsage(String studyStr, String fileId, long size, String sessionId) throws CatalogException {
MyResource<File> resource = getUid(fileId, studyStr, sessionId);
authorizationManager.checkFilePermission(resource.getStudy().getUid(), resource.getResource().getUid(), resource.getUser(),
FileAclEntry.FilePermissions.WRITE);
ObjectMap parameters = new ObjectMap(FileDBAdaptor.QueryParams.SIZE.key(), size);
fileDBAdaptor.update(resource.getResource().getUid(), parameters, QueryOptions.empty());
auditManager.recordUpdate(AuditRecord.Resource.file, resource.getResource().getUid(), resource.getUser(), parameters, null, null);
}
@Deprecated
public void setModificationDate(String studyStr, String fileId, String date, String sessionId) throws CatalogException {
MyResource<File> resource = getUid(fileId, studyStr, sessionId);
String userId = resource.getUser();
long studyId = resource.getStudy().getUid();
authorizationManager.checkFilePermission(studyId, resource.getResource().getUid(), userId, FileAclEntry.FilePermissions.WRITE);
ObjectMap parameters = new ObjectMap(FileDBAdaptor.QueryParams.MODIFICATION_DATE.key(), date);
fileDBAdaptor.update(resource.getResource().getUid(), parameters, QueryOptions.empty());
auditManager.recordUpdate(AuditRecord.Resource.file, resource.getResource().getUid(), userId, parameters, null, null);
}
public void setUri(String studyStr, String fileId, String uri, String sessionId) throws CatalogException {
MyResource<File> resource = getUid(fileId, studyStr, sessionId);
String userId = resource.getUser();
long studyId = resource.getStudy().getUid();
authorizationManager.checkFilePermission(studyId, resource.getResource().getUid(), userId, FileAclEntry.FilePermissions.WRITE);
ObjectMap parameters = new ObjectMap(FileDBAdaptor.QueryParams.URI.key(), uri);
fileDBAdaptor.update(resource.getResource().getUid(), parameters, QueryOptions.empty());
auditManager.recordUpdate(AuditRecord.Resource.file, resource.getResource().getUid(), userId, parameters, null, null);
}
// ************************** ACLs ******************************** //
public List<QueryResult<FileAclEntry>> getAcls(String studyStr, List<String> fileList, String member, boolean silent, String sessionId)
throws CatalogException {
List<QueryResult<FileAclEntry>> fileAclList = new ArrayList<>(fileList.size());
for (String file : fileList) {
try {
MyResource<File> resource = getUid(file, studyStr, sessionId);
QueryResult<FileAclEntry> allFileAcls;
if (StringUtils.isNotEmpty(member)) {
allFileAcls = authorizationManager.getFileAcl(resource.getStudy().getUid(), resource.getResource().getUid(),
resource.getUser(), member);
} else {
allFileAcls = authorizationManager.getAllFileAcls(resource.getStudy().getUid(), resource.getResource().getUid(),
resource.getUser(), true);
}
allFileAcls.setId(file);
fileAclList.add(allFileAcls);
} catch (CatalogException e) {
if (silent) {
fileAclList.add(new QueryResult<>(file, 0, 0, 0, "", e.toString(), new ArrayList<>(0)));
} else {
throw e;
}
}
}
return fileAclList;
}
public List<QueryResult<FileAclEntry>> updateAcl(String studyStr, List<String> fileList, String memberIds,
File.FileAclParams fileAclParams, String sessionId) throws CatalogException {
int count = 0;
count += fileList != null && !fileList.isEmpty() ? 1 : 0;
count += StringUtils.isNotEmpty(fileAclParams.getSample()) ? 1 : 0;
if (count > 1) {
throw new CatalogException("Update ACL: Only one of these parameters are allowed: file or sample per query.");
} else if (count == 0) {
throw new CatalogException("Update ACL: At least one of these parameters should be provided: file or sample");
}
if (fileAclParams.getAction() == null) {
throw new CatalogException("Invalid action found. Please choose a valid action to be performed.");
}
List<String> permissions = Collections.emptyList();
if (StringUtils.isNotEmpty(fileAclParams.getPermissions())) {
permissions = Arrays.asList(fileAclParams.getPermissions().trim().replaceAll("\\s", "").split(","));
checkPermissions(permissions, FileAclEntry.FilePermissions::valueOf);
}
if (StringUtils.isNotEmpty(fileAclParams.getSample())) {
// Obtain the sample ids
MyResources<Sample> resource = catalogManager.getSampleManager().getUids(
Arrays.asList(StringUtils.split(fileAclParams.getSample(), ",")), studyStr, sessionId);
Query query = new Query(FileDBAdaptor.QueryParams.SAMPLE_UIDS.key(), resource.getResourceList().stream().map(Sample::getUid)
.collect(Collectors.toList()));
QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, FileDBAdaptor.QueryParams.UID.key());
QueryResult<File> fileQueryResult = catalogManager.getFileManager().get(studyStr, query, options, sessionId);
fileList = fileQueryResult.getResult().stream().map(File::getUid).map(String::valueOf).collect(Collectors.toList());
}
// Obtain the resource ids
MyResources<File> resource = getUids(fileList, studyStr, sessionId);
authorizationManager.checkCanAssignOrSeePermissions(resource.getStudy().getUid(), resource.getUser());
// Increase the list with the files/folders within the list of ids that correspond with folders
resource = getRecursiveFilesAndFolders(resource);
// Validate that the members are actually valid members
List<String> members;
if (memberIds != null && !memberIds.isEmpty()) {
members = Arrays.asList(memberIds.split(","));
} else {
members = Collections.emptyList();
}
authorizationManager.checkNotAssigningPermissionsToAdminsGroup(members);
checkMembers(resource.getStudy().getUid(), members);
// catalogManager.getStudyManager().membersHavePermissionsInStudy(resourceIds.getStudyId(), members);
switch (fileAclParams.getAction()) {
case SET:
// Todo: Remove this in 1.4
List<String> allFilePermissions = EnumSet.allOf(FileAclEntry.FilePermissions.class)
.stream()
.map(String::valueOf)
.collect(Collectors.toList());
return authorizationManager.setAcls(resource.getStudy().getUid(), resource.getResourceList().stream().map(File::getUid)
.collect(Collectors.toList()), members, permissions, allFilePermissions, Entity.FILE);
case ADD:
return authorizationManager.addAcls(resource.getStudy().getUid(), resource.getResourceList().stream().map(File::getUid)
.collect(Collectors.toList()), members, permissions, Entity.FILE);
case REMOVE:
return authorizationManager.removeAcls(resource.getResourceList().stream().map(File::getUid).collect(Collectors.toList()),
members, permissions, Entity.FILE);
case RESET:
return authorizationManager.removeAcls(resource.getResourceList().stream().map(File::getUid).collect(Collectors.toList()),
members, null, Entity.FILE);
default:
throw new CatalogException("Unexpected error occurred. No valid action found.");
}
}
// ************************** Private methods ******************************** //
private boolean isRootFolder(File file) throws CatalogException {
ParamUtils.checkObj(file, "File");
return file.getPath().isEmpty();
}
/**
* Fetch all the recursive files and folders within the list of file ids given.
*
* @param resource ResourceId object containing the list of file ids, studyId and userId.
* @return a new ResourceId object
*/
private MyResources<File> getRecursiveFilesAndFolders(MyResources<File> resource) throws CatalogException {
List<File> fileList = new LinkedList<>();
fileList.addAll(resource.getResourceList());
Set<Long> uidFileSet = new HashSet<>();
uidFileSet.addAll(resource.getResourceList().stream().map(File::getUid).collect(Collectors.toSet()));
List<String> pathList = new ArrayList<>();
for (File file : resource.getResourceList()) {
if (file.getType().equals(File.Type.DIRECTORY)) {
pathList.add("~^" + file.getPath());
}
}
QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, FileDBAdaptor.QueryParams.UID.key());
if (CollectionUtils.isNotEmpty(pathList)) {
// Search for all the files within the list of paths
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), resource.getStudy().getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), pathList);
QueryResult<File> fileQueryResult1 = fileDBAdaptor.get(query, options);
for (File file1 : fileQueryResult1.getResult()) {
if (!uidFileSet.contains(file1.getUid())) {
uidFileSet.add(file1.getUid());
fileList.add(file1);
}
}
}
return new MyResources<>(resource.getUser(), resource.getStudy(), fileList);
}
private List<String> getParentPaths(String filePath) {
String path = "";
String[] split = filePath.split("/");
List<String> paths = new ArrayList<>(split.length + 1);
paths.add(""); //Add study root folder
//Add intermediate folders
//Do not add the last split, could be a file or a folder..
//Depending on this, it could end with '/' or not.
for (int i = 0; i < split.length - 1; i++) {
String f = split[i];
path = path + f + "/";
paths.add(path);
}
paths.add(filePath); //Add the file path
return paths;
}
@Override
File smartResolutor(long studyUid, String fileName, String user) throws CatalogException {
if (UUIDUtils.isOpenCGAUUID(fileName)) {
// We search as uuid
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyUid)
.append(FileDBAdaptor.QueryParams.UUID.key(), fileName);
QueryResult<File> pathQueryResult = fileDBAdaptor.get(query, QueryOptions.empty());
if (pathQueryResult.getNumResults() > 1) {
throw new CatalogException("Error: More than one file id found based on " + fileName);
} else if (pathQueryResult.getNumResults() == 1) {
return pathQueryResult.first();
}
}
fileName = fileName.replace(":", "/");
if (fileName.startsWith("/")) {
fileName = fileName.substring(1);
}
// We search as a path
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyUid)
.append(FileDBAdaptor.QueryParams.PATH.key(), fileName);
QueryResult<File> pathQueryResult = fileDBAdaptor.get(query, QueryOptions.empty());
if (pathQueryResult.getNumResults() > 1) {
throw new CatalogException("Error: More than one file id found based on " + fileName);
} else if (pathQueryResult.getNumResults() == 1) {
return pathQueryResult.first();
}
if (!fileName.contains("/")) {
// We search as a fileName as well
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyUid)
.append(FileDBAdaptor.QueryParams.NAME.key(), fileName);
QueryResult<File> nameQueryResult = fileDBAdaptor.get(query, QueryOptions.empty());
if (nameQueryResult.getNumResults() > 1) {
throw new CatalogException("Error: More than one file id found based on " + fileName);
} else if (nameQueryResult.getNumResults() == 1) {
return nameQueryResult.first();
}
}
throw new CatalogException("File " + fileName + " not found");
}
//FIXME: This should use org.opencb.opencga.storage.core.variant.io.VariantReaderUtils
private String getOriginalFile(String name) {
if (name.endsWith(".variants.avro.gz")
|| name.endsWith(".variants.proto.gz")
|| name.endsWith(".variants.json.gz")) {
int idx = name.lastIndexOf(".variants.");
return name.substring(0, idx);
} else {
return null;
}
}
private boolean isTransformedFile(String name) {
return getOriginalFile(name) != null;
}
private String getMetaFile(String path) {
String file = getOriginalFile(path);
if (file != null) {
return file + ".file.json.gz";
} else {
return null;
}
}
private QueryResult<File> getParents(boolean rootFirst, QueryOptions options, String filePath, long studyId) throws CatalogException {
List<String> paths = getParentPaths(filePath);
Query query = new Query(FileDBAdaptor.QueryParams.PATH.key(), paths);
query.put(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId);
QueryResult<File> result = fileDBAdaptor.get(query, options);
result.getResult().sort(rootFirst ? ROOT_FIRST_COMPARATOR : ROOT_LAST_COMPARATOR);
return result;
}
private String getParentPath(String path) {
Path parent = Paths.get(path).getParent();
String parentPath;
if (parent == null) { //If parent == null, the file is in the root of the study
parentPath = "";
} else {
parentPath = parent.toString() + "/";
}
return parentPath;
}
/**
* Get the URI where a file should be in Catalog, given a study and a path.
*
* @param studyId Study identifier
* @param path Path to locate
* @param directory Boolean indicating if the file is a directory
* @return URI where the file should be placed
* @throws CatalogException CatalogException
*/
private URI getFileUri(long studyId, String path, boolean directory) throws CatalogException, URISyntaxException {
// Get the closest existing parent. If parents == true, may happen that the parent is not registered in catalog yet.
File existingParent = getParents(false, null, path, studyId).first();
//Relative path to the existing parent
String relativePath = Paths.get(existingParent.getPath()).relativize(Paths.get(path)).toString();
if (path.endsWith("/") && !relativePath.endsWith("/")) {
relativePath += "/";
}
String uriStr = Paths.get(existingParent.getUri().getPath()).resolve(relativePath).toString();
if (directory) {
return UriUtils.createDirectoryUri(uriStr);
} else {
return UriUtils.createUri(uriStr);
}
}
private boolean isExternal(Study study, String catalogFilePath, URI fileUri) throws CatalogException {
URI studyUri = study.getUri();
String studyFilePath = studyUri.resolve(catalogFilePath).getPath();
String originalFilePath = fileUri.getPath();
logger.info("Study file path: {}", studyFilePath);
logger.info("File path: {}", originalFilePath);
return !studyFilePath.equals(originalFilePath);
}
private FileTree getTree(File folder, Query query, QueryOptions queryOptions, int maxDepth, long studyId, String userId)
throws CatalogDBException {
if (maxDepth == 0) {
return null;
}
try {
authorizationManager.checkFilePermission(studyId, folder.getUid(), userId, FileAclEntry.FilePermissions.VIEW);
} catch (CatalogException e) {
return null;
}
// Update the new path to be looked for
query.put(FileDBAdaptor.QueryParams.DIRECTORY.key(), folder.getPath());
FileTree fileTree = new FileTree(folder);
List<FileTree> children = new ArrayList<>();
// Obtain the files and directories inside the directory
QueryResult<File> fileQueryResult = fileDBAdaptor.get(query, queryOptions);
for (File fileAux : fileQueryResult.getResult()) {
if (fileAux.getType().equals(File.Type.DIRECTORY)) {
FileTree subTree = getTree(fileAux, query, queryOptions, maxDepth - 1, studyId, userId);
if (subTree != null) {
children.add(subTree);
}
} else {
try {
authorizationManager.checkFilePermission(studyId, fileAux.getUid(), userId, FileAclEntry.FilePermissions.VIEW);
children.add(new FileTree(fileAux));
} catch (CatalogException e) {
continue;
}
}
}
fileTree.setChildren(children);
return fileTree;
}
private int countFilesInTree(FileTree fileTree) {
int count = 1;
for (FileTree tree : fileTree.getChildren()) {
count += countFilesInTree(tree);
}
return count;
}
/**
* Method to check if a files matching a query can be deleted. It will only be possible to delete files as long as they are not indexed.
*
* @param query Query object.
* @param physicalDelete boolean indicating whether the files matching the query should be completely deleted from the file system or
* they should be sent to the trash bin.
* @param studyId Study where the query will be applied.
* @param userId user for which DELETE permissions will be checked.
* @return the list of files scanned that can be deleted.
* @throws CatalogException if any of the files cannot be deleted.
*/
public List<File> checkCanDeleteFiles(Query query, boolean physicalDelete, long studyId, String userId) throws CatalogException {
String statusQuery = physicalDelete ? GET_NON_DELETED_FILES : GET_NON_TRASHED_FILES;
QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(FileDBAdaptor.QueryParams.UID.key(),
FileDBAdaptor.QueryParams.NAME.key(), FileDBAdaptor.QueryParams.TYPE.key(), FileDBAdaptor.QueryParams.RELATED_FILES.key(),
FileDBAdaptor.QueryParams.SIZE.key(), FileDBAdaptor.QueryParams.URI.key(), FileDBAdaptor.QueryParams.PATH.key(),
FileDBAdaptor.QueryParams.INDEX.key(), FileDBAdaptor.QueryParams.STATUS.key(), FileDBAdaptor.QueryParams.EXTERNAL.key()));
Query myQuery = new Query(query);
myQuery.put(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId);
myQuery.put(FileDBAdaptor.QueryParams.STATUS_NAME.key(), statusQuery);
QueryResult<File> fileQueryResult = fileDBAdaptor.get(myQuery, options);
return checkCanDeleteFiles(fileQueryResult.getResult().iterator(), physicalDelete, String.valueOf(studyId), userId);
}
public List<File> checkCanDeleteFiles(Iterator<File> fileIterator, boolean physicalDelete, String studyStr, String userId)
throws CatalogException {
List<File> filesChecked = new LinkedList<>();
while (fileIterator.hasNext()) {
filesChecked.addAll(checkCanDeleteFile(studyStr, fileIterator.next(), physicalDelete, userId));
}
return filesChecked;
}
public List<File> checkCanDeleteFile(String studyStr, File file, boolean physicalDelete, String userId) throws CatalogException {
String statusQuery = physicalDelete ? GET_NON_DELETED_FILES : GET_NON_TRASHED_FILES;
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId);
QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(FileDBAdaptor.QueryParams.UID.key(),
FileDBAdaptor.QueryParams.NAME.key(), FileDBAdaptor.QueryParams.TYPE.key(), FileDBAdaptor.QueryParams.RELATED_FILES.key(),
FileDBAdaptor.QueryParams.SIZE.key(), FileDBAdaptor.QueryParams.URI.key(), FileDBAdaptor.QueryParams.PATH.key(),
FileDBAdaptor.QueryParams.INDEX.key(), FileDBAdaptor.QueryParams.STATUS.key(), FileDBAdaptor.QueryParams.EXTERNAL.key()));
List<File> filesToAnalyse = new LinkedList<>();
if (file.getType() == File.Type.FILE) {
filesToAnalyse.add(file);
} else {
// We cannot delete the root folder
if (isRootFolder(file)) {
throw new CatalogException("Root directories cannot be deleted");
}
// Get all recursive files and folders
Query newQuery = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + file.getPath() + "*")
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), statusQuery);
QueryResult<File> recursiveFileQueryResult = fileDBAdaptor.get(newQuery, options);
if (file.isExternal()) {
// Check there aren't local files within the directory
List<String> wrongFiles = new LinkedList<>();
for (File nestedFile : recursiveFileQueryResult.getResult()) {
if (!nestedFile.isExternal()) {
wrongFiles.add(nestedFile.getPath());
}
}
if (!wrongFiles.isEmpty()) {
throw new CatalogException("Local files {" + StringUtils.join(wrongFiles, ", ") + "} detected within the external "
+ "folder " + file.getPath() + ". Please, delete those folders or files manually first");
}
} else {
// Check there aren't external files within the directory
List<String> wrongFiles = new LinkedList<>();
for (File nestedFile : recursiveFileQueryResult.getResult()) {
if (nestedFile.isExternal()) {
wrongFiles.add(nestedFile.getPath());
}
}
if (!wrongFiles.isEmpty()) {
throw new CatalogException("External files {" + StringUtils.join(wrongFiles, ", ") + "} detected within the local "
+ "folder " + file.getPath() + ". Please, unlink those folders or files manually first");
}
}
filesToAnalyse.addAll(recursiveFileQueryResult.getResult());
}
// If the user is the owner or the admin, we won't check if he has permissions for every single file
boolean checkPermissions = !authorizationManager.checkIsOwnerOrAdmin(study.getUid(), userId);
Set<Long> transformedFromFileIds = new HashSet<>();
for (File fileAux : filesToAnalyse) {
if (checkPermissions) {
authorizationManager.checkFilePermission(study.getUid(), fileAux.getUid(), userId, FileAclEntry.FilePermissions.DELETE);
}
// Check the file status is not STAGE or MISSING
if (fileAux.getStatus() == null) {
throw new CatalogException("Cannot check file status for deletion");
}
if (File.FileStatus.STAGE.equals(fileAux.getStatus().getName())
|| File.FileStatus.MISSING.equals(fileAux.getStatus().getName())) {
throw new CatalogException("Cannot delete file: " + fileAux.getName() + ". The status is " + fileAux.getStatus().getName());
}
// Check the index status
if (fileAux.getIndex() != null && fileAux.getIndex().getStatus() != null
&& !FileIndex.IndexStatus.NONE.equals(fileAux.getIndex().getStatus().getName())
&& !FileIndex.IndexStatus.TRANSFORMED.equals(fileAux.getIndex().getStatus().getName())) {
throw new CatalogException("Cannot delete file: " + fileAux.getName() + ". The index status is "
+ fileAux.getIndex().getStatus().getName());
}
// Check if the file is produced from other file being indexed and add them to the transformedFromFileIds set
if (fileAux.getRelatedFiles() != null && !fileAux.getRelatedFiles().isEmpty()) {
transformedFromFileIds.addAll(
fileAux.getRelatedFiles().stream()
.filter(myFile -> myFile.getRelation() == File.RelatedFile.Relation.PRODUCED_FROM)
.map(File.RelatedFile::getFileId)
.collect(Collectors.toSet())
);
}
}
// Check the original files are not being indexed at the moment
if (!transformedFromFileIds.isEmpty()) {
Query query = new Query(FileDBAdaptor.QueryParams.UID.key(), new ArrayList<>(transformedFromFileIds));
try (DBIterator<File> iterator = fileDBAdaptor.iterator(query, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(
FileDBAdaptor.QueryParams.INDEX.key(), FileDBAdaptor.QueryParams.UID.key())))) {
while (iterator.hasNext()) {
File next = iterator.next();
String status = next.getIndex().getStatus().getName();
switch (status) {
case FileIndex.IndexStatus.READY:
// If they are already ready, we only need to remove the reference to the transformed files as they will be
// removed
next.getIndex().setTransformedFile(null);
break;
case FileIndex.IndexStatus.TRANSFORMED:
// We need to remove the reference to the transformed files and change their status from TRANSFORMED to NONE
next.getIndex().setTransformedFile(null);
next.getIndex().getStatus().setName(FileIndex.IndexStatus.NONE);
break;
case FileIndex.IndexStatus.NONE:
case FileIndex.IndexStatus.DELETED:
break;
default:
throw new CatalogException("Cannot delete files that are in use in storage.");
}
}
}
}
return filesToAnalyse;
}
public FacetQueryResult facet(String studyStr, Query query, QueryOptions queryOptions, boolean defaultStats, String sessionId)
throws CatalogException, IOException {
ParamUtils.defaultObject(query, Query::new);
ParamUtils.defaultObject(queryOptions, QueryOptions::new);
if (defaultStats || StringUtils.isEmpty(queryOptions.getString(QueryOptions.FACET))) {
String facet = queryOptions.getString(QueryOptions.FACET);
queryOptions.put(QueryOptions.FACET, StringUtils.isNotEmpty(facet) ? defaultFacet + ";" + facet : defaultFacet);
}
CatalogSolrManager catalogSolrManager = new CatalogSolrManager(catalogManager);
String userId = userManager.getUserId(sessionId);
// We need to add variableSets and groups to avoid additional queries as it will be used in the catalogSolrManager
Study study = catalogManager.getStudyManager().resolveId(studyStr, userId, new QueryOptions(QueryOptions.INCLUDE,
Arrays.asList(StudyDBAdaptor.QueryParams.VARIABLE_SET.key(), StudyDBAdaptor.QueryParams.GROUPS.key())));
AnnotationUtils.fixQueryAnnotationSearch(study, userId, query, authorizationManager);
return catalogSolrManager.facetedQuery(study, CatalogSolrManager.FILE_SOLR_COLLECTION, query, queryOptions, userId);
}
private void updateIndexStatusAfterDeletionOfTransformedFile(long studyId, File file) throws CatalogDBException {
if (file.getType() == File.Type.FILE && (file.getRelatedFiles() == null || file.getRelatedFiles().isEmpty())) {
return;
}
// We check if any of the files to be removed are transformation files
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), "~^" + file.getPath() + "*")
.append(FileDBAdaptor.QueryParams.RELATED_FILES_RELATION.key(), File.RelatedFile.Relation.PRODUCED_FROM);
QueryResult<File> fileQR = fileDBAdaptor.get(query, new QueryOptions(QueryOptions.INCLUDE,
FileDBAdaptor.QueryParams.RELATED_FILES.key()));
if (fileQR.getNumResults() > 0) {
// Among the files to be deleted / unlinked, there are transformed files. We need to check that these files are not being used
// anymore.
Set<Long> fileIds = new HashSet<>();
for (File transformedFile : fileQR.getResult()) {
fileIds.addAll(
transformedFile.getRelatedFiles().stream()
.filter(myFile -> myFile.getRelation() == File.RelatedFile.Relation.PRODUCED_FROM)
.map(File.RelatedFile::getFileId)
.collect(Collectors.toSet())
);
}
// Update the original files to remove the transformed file
query = new Query(FileDBAdaptor.QueryParams.UID.key(), new ArrayList<>(fileIds));
Map<Long, FileIndex> filesToUpdate;
try (DBIterator<File> iterator = fileDBAdaptor.iterator(query, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(
FileDBAdaptor.QueryParams.INDEX.key(), FileDBAdaptor.QueryParams.UID.key())))) {
filesToUpdate = new HashMap<>();
while (iterator.hasNext()) {
File next = iterator.next();
String status = next.getIndex().getStatus().getName();
switch (status) {
case FileIndex.IndexStatus.READY:
// If they are already ready, we only need to remove the reference to the transformed files as they will be
// removed
next.getIndex().setTransformedFile(null);
filesToUpdate.put(next.getUid(), next.getIndex());
break;
case FileIndex.IndexStatus.TRANSFORMED:
// We need to remove the reference to the transformed files and change their status from TRANSFORMED to NONE
next.getIndex().setTransformedFile(null);
next.getIndex().getStatus().setName(FileIndex.IndexStatus.NONE);
filesToUpdate.put(next.getUid(), next.getIndex());
break;
default:
break;
}
}
}
for (Map.Entry<Long, FileIndex> indexEntry : filesToUpdate.entrySet()) {
fileDBAdaptor.update(indexEntry.getKey(), new ObjectMap(FileDBAdaptor.QueryParams.INDEX.key(), indexEntry.getValue()),
QueryOptions.empty());
}
}
}
/**
* Create the parent directories that are needed.
*
* @param study study where they will be created.
* @param userId user that is creating the parents.
* @param studyURI Base URI where the created folders will be pointing to. (base physical location)
* @param path Path used in catalog as a virtual location. (whole bunch of directories inside the virtual
* location in catalog)
* @param checkPermissions Boolean indicating whether to check if the user has permissions to create a folder in the first directory
* that is available in catalog.
* @throws CatalogDBException
*/
private void createParents(Study study, String userId, URI studyURI, Path path, boolean checkPermissions) throws CatalogException {
if (path == null) {
if (checkPermissions) {
authorizationManager.checkStudyPermission(study.getUid(), userId, StudyAclEntry.StudyPermissions.WRITE_FILES);
}
return;
}
String stringPath = path.toString();
if (("/").equals(stringPath)) {
return;
}
logger.info("Path: {}", stringPath);
if (stringPath.startsWith("/")) {
stringPath = stringPath.substring(1);
}
if (!stringPath.endsWith("/")) {
stringPath = stringPath + "/";
}
// Check if the folder exists
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), stringPath);
if (fileDBAdaptor.count(query).first() == 0) {
createParents(study, userId, studyURI, path.getParent(), checkPermissions);
} else {
if (checkPermissions) {
long fileId = fileDBAdaptor.getId(study.getUid(), stringPath);
authorizationManager.checkFilePermission(study.getUid(), fileId, userId, FileAclEntry.FilePermissions.WRITE);
}
return;
}
String parentPath = getParentPath(stringPath);
long parentFileId = fileDBAdaptor.getId(study.getUid(), parentPath);
// We obtain the permissions set in the parent folder and set them to the file or folder being created
QueryResult<FileAclEntry> allFileAcls = authorizationManager.getAllFileAcls(study.getUid(), parentFileId, userId, checkPermissions);
URI completeURI = Paths.get(studyURI).resolve(path).toUri();
// Create the folder in catalog
File folder = new File(path.getFileName().toString(), File.Type.DIRECTORY, File.Format.PLAIN, File.Bioformat.NONE, completeURI,
stringPath, null, TimeUtils.getTime(), TimeUtils.getTime(), "", new File.FileStatus(File.FileStatus.READY), false, 0, null,
new Experiment(), Collections.emptyList(), new Job(), Collections.emptyList(), null,
catalogManager.getStudyManager().getCurrentRelease(study, userId), Collections.emptyList(), null, null);
folder.setUuid(UUIDUtils.generateOpenCGAUUID(UUIDUtils.Entity.FILE));
checkHooks(folder, study.getFqn(), HookConfiguration.Stage.CREATE);
QueryResult<File> queryResult = fileDBAdaptor.insert(study.getUid(), folder, Collections.emptyList(), new QueryOptions());
// Propagate ACLs
if (allFileAcls != null && allFileAcls.getNumResults() > 0) {
authorizationManager.replicateAcls(study.getUid(), Arrays.asList(queryResult.first().getUid()), allFileAcls.getResult(),
Entity.FILE);
}
}
private QueryResult<File> privateLink(Study study, URI uriOrigin, String pathDestiny, ObjectMap params, String sessionId)
throws CatalogException, IOException {
params = ParamUtils.defaultObject(params, ObjectMap::new);
CatalogIOManager ioManager = catalogIOManagerFactory.get(uriOrigin);
if (!ioManager.exists(uriOrigin)) {
throw new CatalogIOException("File " + uriOrigin + " does not exist");
}
final URI normalizedUri;
try {
normalizedUri = UriUtils.createUri(uriOrigin.normalize().getPath());
} catch (URISyntaxException e) {
throw new CatalogException(e);
}
String userId = userManager.getUserId(sessionId);
authorizationManager.checkStudyPermission(study.getUid(), userId, StudyAclEntry.StudyPermissions.WRITE_FILES);
pathDestiny = ParamUtils.defaultString(pathDestiny, "");
if (pathDestiny.length() == 1 && (pathDestiny.equals(".") || pathDestiny.equals("/"))) {
pathDestiny = "";
} else {
if (pathDestiny.startsWith("/")) {
pathDestiny = pathDestiny.substring(1);
}
if (!pathDestiny.isEmpty() && !pathDestiny.endsWith("/")) {
pathDestiny = pathDestiny + "/";
}
}
String externalPathDestinyStr;
if (Paths.get(normalizedUri).toFile().isDirectory()) {
externalPathDestinyStr = Paths.get(pathDestiny).resolve(Paths.get(normalizedUri).getFileName()).toString() + "/";
} else {
externalPathDestinyStr = Paths.get(pathDestiny).resolve(Paths.get(normalizedUri).getFileName()).toString();
}
// Check if the path already exists and is not external
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), "!=" + File.FileStatus.TRASHED + ";!=" + Status.DELETED + ";!="
+ File.FileStatus.REMOVED)
.append(FileDBAdaptor.QueryParams.PATH.key(), externalPathDestinyStr)
.append(FileDBAdaptor.QueryParams.EXTERNAL.key(), false);
if (fileDBAdaptor.count(query).first() > 0) {
throw new CatalogException("Cannot link to " + externalPathDestinyStr + ". The path already existed and is not external.");
}
// Check if the uri was already linked to that same path
query = new Query()
.append(FileDBAdaptor.QueryParams.URI.key(), normalizedUri)
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), "!=" + File.FileStatus.TRASHED + ";!=" + Status.DELETED + ";!="
+ File.FileStatus.REMOVED)
.append(FileDBAdaptor.QueryParams.PATH.key(), externalPathDestinyStr)
.append(FileDBAdaptor.QueryParams.EXTERNAL.key(), true);
if (fileDBAdaptor.count(query).first() > 0) {
// Create a regular expression on URI to return everything linked from that URI
query.put(FileDBAdaptor.QueryParams.URI.key(), "~^" + normalizedUri);
query.remove(FileDBAdaptor.QueryParams.PATH.key());
// Limit the number of results and only some fields
QueryOptions queryOptions = new QueryOptions()
.append(QueryOptions.LIMIT, 100);
return fileDBAdaptor.get(query, queryOptions);
}
// Check if the uri was linked to other path
query = new Query()
.append(FileDBAdaptor.QueryParams.URI.key(), normalizedUri)
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), "!=" + File.FileStatus.TRASHED + ";!=" + Status.DELETED + ";!="
+ File.FileStatus.REMOVED)
.append(FileDBAdaptor.QueryParams.EXTERNAL.key(), true);
if (fileDBAdaptor.count(query).first() > 0) {
QueryOptions queryOptions = new QueryOptions(QueryOptions.INCLUDE, FileDBAdaptor.QueryParams.PATH.key());
String path = fileDBAdaptor.get(query, queryOptions).first().getPath();
throw new CatalogException(normalizedUri + " was already linked to other path: " + path);
}
boolean parents = params.getBoolean("parents", false);
// FIXME: Implement resync
boolean resync = params.getBoolean("resync", false);
String description = params.getString("description", "");
String checksum = params.getString(FileDBAdaptor.QueryParams.CHECKSUM.key(), "");
// Because pathDestiny can be null, we will use catalogPath as the virtual destiny where the files will be located in catalog.
Path catalogPath = Paths.get(pathDestiny);
if (pathDestiny.isEmpty()) {
// If no destiny is given, everything will be linked to the root folder of the study.
authorizationManager.checkStudyPermission(study.getUid(), userId, StudyAclEntry.StudyPermissions.WRITE_FILES);
} else {
// Check if the folder exists
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), pathDestiny);
if (fileDBAdaptor.count(query).first() == 0) {
if (parents) {
// Get the base URI where the files are located in the study
URI studyURI = study.getUri();
createParents(study, userId, studyURI, catalogPath, true);
// Create them in the disk
// URI directory = Paths.get(studyURI).resolve(catalogPath).toUri();
// catalogIOManagerFactory.get(directory).createDirectory(directory, true);
} else {
throw new CatalogException("The path " + catalogPath + " does not exist in catalog.");
}
} else {
// Check if the user has permissions to link files in the directory
long fileId = fileDBAdaptor.getId(study.getUid(), pathDestiny);
authorizationManager.checkFilePermission(study.getUid(), fileId, userId, FileAclEntry.FilePermissions.WRITE);
}
}
Path pathOrigin = Paths.get(normalizedUri);
Path externalPathDestiny = Paths.get(externalPathDestinyStr);
if (Paths.get(normalizedUri).toFile().isFile()) {
// Check if there is already a file in the same path
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), externalPathDestinyStr);
// Create the file
if (fileDBAdaptor.count(query).first() == 0) {
long size = Files.size(Paths.get(normalizedUri));
String parentPath = getParentPath(externalPathDestinyStr);
long parentFileId = fileDBAdaptor.getId(study.getUid(), parentPath);
// We obtain the permissions set in the parent folder and set them to the file or folder being created
QueryResult<FileAclEntry> allFileAcls = authorizationManager.getAllFileAcls(study.getUid(), parentFileId, userId, true);
File subfile = new File(externalPathDestiny.getFileName().toString(), File.Type.FILE, File.Format.UNKNOWN,
File.Bioformat.NONE, normalizedUri, externalPathDestinyStr, checksum, TimeUtils.getTime(), TimeUtils.getTime(),
description, new File.FileStatus(File.FileStatus.READY), true, size, null, new Experiment(),
Collections.emptyList(), new Job(), Collections.emptyList(), null,
catalogManager.getStudyManager().getCurrentRelease(study, userId), Collections.emptyList(), Collections.emptyMap(),
Collections.emptyMap());
subfile.setUuid(UUIDUtils.generateOpenCGAUUID(UUIDUtils.Entity.FILE));
checkHooks(subfile, study.getFqn(), HookConfiguration.Stage.CREATE);
QueryResult<File> queryResult = fileDBAdaptor.insert(study.getUid(), subfile, Collections.emptyList(), new QueryOptions());
// Propagate ACLs
if (allFileAcls != null && allFileAcls.getNumResults() > 0) {
authorizationManager.replicateAcls(study.getUid(), Arrays.asList(queryResult.first().getUid()), allFileAcls.getResult(),
Entity.FILE);
}
File file = this.file.setMetadataInformation(queryResult.first(), queryResult.first().getUri(),
new QueryOptions(), sessionId, false);
queryResult.setResult(Arrays.asList(file));
// If it is a transformed file, we will try to link it with the correspondent original file
try {
if (isTransformedFile(file.getName())) {
matchUpVariantFiles(study.getFqn(), Arrays.asList(file), sessionId);
}
} catch (CatalogException e) {
logger.warn("Matching avro to variant file: {}", e.getMessage());
}
return queryResult;
} else {
throw new CatalogException("Cannot link " + externalPathDestiny.getFileName().toString() + ". A file with the same name "
+ "was found in the same path.");
}
} else {
// This list will contain the list of transformed files detected during the link
List<File> transformedFiles = new ArrayList<>();
// We remove the / at the end for replacement purposes in the walkFileTree
String finalExternalPathDestinyStr = externalPathDestinyStr.substring(0, externalPathDestinyStr.length() - 1);
// Link all the files and folders present in the uri
Files.walkFileTree(pathOrigin, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
try {
String destinyPath = dir.toString().replace(Paths.get(normalizedUri).toString(), finalExternalPathDestinyStr);
if (!destinyPath.isEmpty() && !destinyPath.endsWith("/")) {
destinyPath += "/";
}
if (destinyPath.startsWith("/")) {
destinyPath = destinyPath.substring(1);
}
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), destinyPath);
if (fileDBAdaptor.count(query).first() == 0) {
// If the folder does not exist, we create it
String parentPath = getParentPath(destinyPath);
long parentFileId = fileDBAdaptor.getId(study.getUid(), parentPath);
// We obtain the permissions set in the parent folder and set them to the file or folder being created
QueryResult<FileAclEntry> allFileAcls;
try {
allFileAcls = authorizationManager.getAllFileAcls(study.getUid(), parentFileId, userId, true);
} catch (CatalogException e) {
throw new RuntimeException(e);
}
File folder = new File(dir.getFileName().toString(), File.Type.DIRECTORY, File.Format.PLAIN,
File.Bioformat.NONE, dir.toUri(), destinyPath, null, TimeUtils.getTime(),
TimeUtils.getTime(), description, new File.FileStatus(File.FileStatus.READY), true, 0, null,
new Experiment(), Collections.emptyList(), new Job(), Collections.emptyList(),
null, catalogManager.getStudyManager().getCurrentRelease(study, userId), Collections.emptyList(),
Collections.emptyMap(), Collections.emptyMap());
folder.setUuid(UUIDUtils.generateOpenCGAUUID(UUIDUtils.Entity.FILE));
checkHooks(folder, study.getFqn(), HookConfiguration.Stage.CREATE);
QueryResult<File> queryResult = fileDBAdaptor.insert(study.getUid(), folder, Collections.emptyList(),
new QueryOptions());
// Propagate ACLs
if (allFileAcls != null && allFileAcls.getNumResults() > 0) {
authorizationManager.replicateAcls(study.getUid(), Arrays.asList(queryResult.first().getUid()),
allFileAcls.getResult(), Entity.FILE);
}
}
} catch (CatalogException e) {
logger.error("An error occurred when trying to create folder {}", dir.toString());
// e.printStackTrace();
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException {
try {
String destinyPath = filePath.toString().replace(Paths.get(normalizedUri).toString(), finalExternalPathDestinyStr);
if (destinyPath.startsWith("/")) {
destinyPath = destinyPath.substring(1);
}
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.PATH.key(), destinyPath);
if (fileDBAdaptor.count(query).first() == 0) {
long size = Files.size(filePath);
// If the file does not exist, we create it
String parentPath = getParentPath(destinyPath);
long parentFileId = fileDBAdaptor.getId(study.getUid(), parentPath);
// We obtain the permissions set in the parent folder and set them to the file or folder being created
QueryResult<FileAclEntry> allFileAcls;
try {
allFileAcls = authorizationManager.getAllFileAcls(study.getUid(), parentFileId, userId, true);
} catch (CatalogException e) {
throw new RuntimeException(e);
}
File subfile = new File(filePath.getFileName().toString(), File.Type.FILE, File.Format.UNKNOWN,
File.Bioformat.NONE, filePath.toUri(), destinyPath, null, TimeUtils.getTime(),
TimeUtils.getTime(), description, new File.FileStatus(File.FileStatus.READY), true, size, null,
new Experiment(), Collections.emptyList(), new Job(), Collections.emptyList(),
null, catalogManager.getStudyManager().getCurrentRelease(study, userId), Collections.emptyList(),
Collections.emptyMap(), Collections.emptyMap());
subfile.setUuid(UUIDUtils.generateOpenCGAUUID(UUIDUtils.Entity.FILE));
checkHooks(subfile, study.getFqn(), HookConfiguration.Stage.CREATE);
QueryResult<File> queryResult = fileDBAdaptor.insert(study.getUid(), subfile, Collections.emptyList(),
new QueryOptions());
// Propagate ACLs
if (allFileAcls != null && allFileAcls.getNumResults() > 0) {
authorizationManager.replicateAcls(study.getUid(), Arrays.asList(queryResult.first().getUid()),
allFileAcls.getResult(), Entity.FILE);
}
File file = FileManager.this.file.setMetadataInformation(queryResult.first(), queryResult.first().getUri(),
new QueryOptions(), sessionId, false);
if (isTransformedFile(file.getName())) {
logger.info("Detected transformed file {}", file.getPath());
transformedFiles.add(file);
}
} else {
throw new CatalogException("Cannot link the file " + filePath.getFileName().toString()
+ ". There is already a file in the path " + destinyPath + " with the same name.");
}
} catch (CatalogException e) {
logger.error(e.getMessage());
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.SKIP_SUBTREE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
// Try to link transformed files with their corresponding original files if any
try {
if (transformedFiles.size() > 0) {
matchUpVariantFiles(study.getFqn(), transformedFiles, sessionId);
}
} catch (CatalogException e) {
logger.warn("Matching avro to variant file: {}", e.getMessage());
}
// Check if the uri was already linked to that same path
query = new Query()
.append(FileDBAdaptor.QueryParams.URI.key(), "~^" + normalizedUri)
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())
.append(FileDBAdaptor.QueryParams.STATUS_NAME.key(), "!=" + File.FileStatus.TRASHED + ";!=" + Status.DELETED + ";!="
+ File.FileStatus.REMOVED)
.append(FileDBAdaptor.QueryParams.EXTERNAL.key(), true);
// Limit the number of results and only some fields
QueryOptions queryOptions = new QueryOptions()
.append(QueryOptions.LIMIT, 100);
return fileDBAdaptor.get(query, queryOptions);
}
}
private void checkHooks(File file, String fqn, HookConfiguration.Stage stage) throws CatalogException {
Map<String, Map<String, List<HookConfiguration>>> hooks = this.configuration.getHooks();
if (hooks != null && hooks.containsKey(fqn)) {
Map<String, List<HookConfiguration>> entityHookMap = hooks.get(fqn);
List<HookConfiguration> hookList = null;
if (entityHookMap.containsKey(MongoDBAdaptorFactory.FILE_COLLECTION)) {
hookList = entityHookMap.get(MongoDBAdaptorFactory.FILE_COLLECTION);
} else if (entityHookMap.containsKey(MongoDBAdaptorFactory.FILE_COLLECTION.toUpperCase())) {
hookList = entityHookMap.get(MongoDBAdaptorFactory.FILE_COLLECTION.toUpperCase());
}
// We check the hook list
if (hookList != null) {
for (HookConfiguration hookConfiguration : hookList) {
if (hookConfiguration.getStage() != stage) {
continue;
}
String field = hookConfiguration.getField();
if (StringUtils.isEmpty(field)) {
logger.warn("Missing 'field' field from hook configuration");
continue;
}
field = field.toLowerCase();
String filterValue = hookConfiguration.getValue();
if (StringUtils.isEmpty(filterValue)) {
logger.warn("Missing 'value' field from hook configuration");
continue;
}
String value = null;
switch (field) {
case "name":
value = file.getName();
break;
case "format":
value = file.getFormat().name();
break;
case "bioformat":
value = file.getFormat().name();
break;
case "path":
value = file.getPath();
break;
case "description":
value = file.getDescription();
break;
// TODO: At some point, we will also have to consider any field that is not a String
// case "size":
// value = file.getSize();
// break;
default:
break;
}
if (value == null) {
continue;
}
String filterNewValue = hookConfiguration.getWhat();
if (StringUtils.isEmpty(filterNewValue)) {
logger.warn("Missing 'what' field from hook configuration");
continue;
}
String filterWhere = hookConfiguration.getWhere();
if (StringUtils.isEmpty(filterWhere)) {
logger.warn("Missing 'where' field from hook configuration");
continue;
}
filterWhere = filterWhere.toLowerCase();
if (filterValue.startsWith("~")) {
// Regular expression
if (!value.matches(filterValue.substring(1))) {
// If it doesn't match, we will check the next hook of the loop
continue;
}
} else {
if (!value.equals(filterValue)) {
// If it doesn't match, we will check the next hook of the loop
continue;
}
}
// The value matched, so we will perform the action desired by the user
if (hookConfiguration.getAction() == HookConfiguration.Action.ABORT) {
throw new CatalogException("A hook to abort the insertion matched");
}
// We check the field the user wants to update
if (filterWhere.equals(FileDBAdaptor.QueryParams.DESCRIPTION.key())) {
switch (hookConfiguration.getAction()) {
case ADD:
case SET:
file.setDescription(hookConfiguration.getWhat());
break;
case REMOVE:
file.setDescription("");
break;
default:
break;
}
} else if (filterWhere.equals(FileDBAdaptor.QueryParams.TAGS.key())) {
switch (hookConfiguration.getAction()) {
case ADD:
List<String> values;
if (hookConfiguration.getWhat().contains(",")) {
values = Arrays.asList(hookConfiguration.getWhat().split(","));
} else {
values = Collections.singletonList(hookConfiguration.getWhat());
}
List<String> tagsCopy = new ArrayList<>();
if (file.getTags() != null) {
tagsCopy.addAll(file.getTags());
}
tagsCopy.addAll(values);
file.setTags(tagsCopy);
break;
case SET:
if (hookConfiguration.getWhat().contains(",")) {
values = Arrays.asList(hookConfiguration.getWhat().split(","));
} else {
values = Collections.singletonList(hookConfiguration.getWhat());
}
file.setTags(values);
break;
case REMOVE:
file.setTags(Collections.emptyList());
break;
default:
break;
}
} else if (filterWhere.startsWith(FileDBAdaptor.QueryParams.STATS.key())) {
String[] split = StringUtils.split(filterWhere, ".", 2);
String statsField = null;
if (split.length == 2) {
statsField = split[1];
}
switch (hookConfiguration.getAction()) {
case ADD:
if (statsField == null) {
logger.error("Cannot add a value to {} directly. Expected {}.<subfield>",
FileDBAdaptor.QueryParams.STATS.key(), FileDBAdaptor.QueryParams.STATS.key());
continue;
}
List<String> values;
if (hookConfiguration.getWhat().contains(",")) {
values = Arrays.asList(hookConfiguration.getWhat().split(","));
} else {
values = Collections.singletonList(hookConfiguration.getWhat());
}
Object currentStatsValue = file.getStats().get(statsField);
if (currentStatsValue == null) {
file.getStats().put(statsField, values);
} else if (currentStatsValue instanceof Collection) {
((List) currentStatsValue).addAll(values);
} else {
logger.error("Cannot add a value to {} if it is not an array", filterWhere);
continue;
}
break;
case SET:
if (statsField == null) {
logger.error("Cannot set a value to {} directly. Expected {}.<subfield>",
FileDBAdaptor.QueryParams.STATS.key(), FileDBAdaptor.QueryParams.STATS.key());
continue;
}
if (hookConfiguration.getWhat().contains(",")) {
values = Arrays.asList(hookConfiguration.getWhat().split(","));
} else {
values = Collections.singletonList(hookConfiguration.getWhat());
}
file.getStats().put(statsField, values);
break;
case REMOVE:
if (statsField == null) {
file.setStats(Collections.emptyMap());
} else {
file.getStats().remove(statsField);
}
break;
default:
break;
}
} else if (filterWhere.startsWith(FileDBAdaptor.QueryParams.ATTRIBUTES.key())) {
String[] split = StringUtils.split(filterWhere, ".", 2);
String attributesField = null;
if (split.length == 2) {
attributesField = split[1];
}
switch (hookConfiguration.getAction()) {
case ADD:
if (attributesField == null) {
logger.error("Cannot add a value to {} directly. Expected {}.<subfield>",
FileDBAdaptor.QueryParams.ATTRIBUTES.key(), FileDBAdaptor.QueryParams.ATTRIBUTES.key());
continue;
}
List<String> values;
if (hookConfiguration.getWhat().contains(",")) {
values = Arrays.asList(hookConfiguration.getWhat().split(","));
} else {
values = Collections.singletonList(hookConfiguration.getWhat());
}
Object currentStatsValue = file.getAttributes().get(attributesField);
if (currentStatsValue == null) {
file.getAttributes().put(attributesField, values);
} else if (currentStatsValue instanceof Collection) {
((List) currentStatsValue).addAll(values);
} else {
logger.error("Cannot add a value to {} if it is not an array", filterWhere);
continue;
}
break;
case SET:
if (attributesField == null) {
logger.error("Cannot set a value to {} directly. Expected {}.<subfield>",
FileDBAdaptor.QueryParams.ATTRIBUTES.key(), FileDBAdaptor.QueryParams.ATTRIBUTES.key());
continue;
}
if (hookConfiguration.getWhat().contains(",")) {
values = Arrays.asList(hookConfiguration.getWhat().split(","));
} else {
values = Collections.singletonList(hookConfiguration.getWhat());
}
file.getAttributes().put(attributesField, values);
break;
case REMOVE:
if (attributesField == null) {
file.setAttributes(Collections.emptyMap());
} else {
file.getAttributes().remove(attributesField);
}
break;
default:
break;
}
} else {
logger.error("{} field cannot be updated. Please, check the hook configured.", hookConfiguration.getWhere());
}
}
}
}
}
private URI getStudyUri(long studyId) throws CatalogException {
return studyDBAdaptor.get(studyId, INCLUDE_STUDY_URI).first().getUri();
}
private enum CheckPath {
FREE_PATH, FILE_EXISTS, DIRECTORY_EXISTS
}
private CheckPath checkPathExists(String path, long studyId) throws CatalogDBException {
String myPath = path;
if (myPath.endsWith("/")) {
myPath = myPath.substring(0, myPath.length() - 1);
}
// We first look for any file called the same way the directory needs to be called
Query query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), myPath);
QueryResult<Long> fileQueryResult = fileDBAdaptor.count(query);
if (fileQueryResult.first() > 0) {
return CheckPath.FILE_EXISTS;
}
query = new Query()
.append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId)
.append(FileDBAdaptor.QueryParams.PATH.key(), myPath + "/");
fileQueryResult = fileDBAdaptor.count(query);
return fileQueryResult.first() > 0 ? CheckPath.DIRECTORY_EXISTS : CheckPath.FREE_PATH;
}
}
| catalog: Ensure parents of temporary folder exist when uploading a file.
| opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FileManager.java | catalog: Ensure parents of temporary folder exist when uploading a file. | <ide><path>pencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FileManager.java
<ide> try {
<ide> if (!Files.exists(tempFilePath.getParent())) {
<ide> logger.debug("Creating temporal folder: {}", tempFilePath.getParent());
<del> Files.createDirectory(tempFilePath.getParent());
<add> ioManager.createDirectory(tempFilePath.getParent().toUri(), true);
<ide> }
<ide>
<ide> // Start uploading the file to the temporal directory
<del> int read;
<del> byte[] bytes = new byte[1024];
<del>
<ide> // Upload the file to a temporary folder
<del> try (OutputStream out = new FileOutputStream(new java.io.File(tempFilePath.toString()))) {
<del> while ((read = fileInputStream.read(bytes)) != -1) {
<del> out.write(bytes, 0, read);
<del> }
<del> }
<add> Files.copy(fileInputStream, tempFilePath);
<ide> } catch (Exception e) {
<ide> logger.error("Error uploading file {}", file.getName(), e);
<ide> |
|
Java | agpl-3.0 | 248fc440f182907a7f3b7fc1df7544502587d8fc | 0 | wiiam/Personal-Bot,wiiam/Personal-Bot,wiiaam/taylorswift.old,wiiaam/taylorswift.old,wiiam/taylorswift.old,wiiam/taylorswift.old | package bot;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Scanner;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class Server {
// Fields
private static SSLSocketFactory sslfact;
public static Scanner in;
public static PrintStream out;
private static Socket socket;
private static SSLSocket sslsocket;
private static boolean isConnected;
private static String address;
private static int port;
private static boolean useSSL;
private static boolean reading = false;
private static ArrayDeque<String> toserver;
private static ArrayDeque<String> toserverlesspriority;
static Thread thread;
public static void connectTo(String address, int port, boolean useSSL){
Server.address = address;
Server.port = port;
Server.useSSL = useSSL;
try{
toserver = new ArrayDeque<String>();
toserverlesspriority = new ArrayDeque<String>();
if(socket != null)socket.close();
if(sslsocket != null)sslsocket.close();
if(out != null) out.close();
if(in != null) in.close();
if(useSSL){
System.setProperty("javax.net.ssl.trustStore", Config.getPathToKeystore());
try {
X509TrustManager[] tm = new X509TrustManager[] { new X509TrustManager(){
public void checkClientTrusted ( X509Certificate[] cert, String authType ) throws CertificateException {
}
public void checkServerTrusted ( X509Certificate[] cert, String authType ) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers (){
return null;
}
}};
SSLContext context = SSLContext.getInstance ("SSL");
context.init( new KeyManager[0], tm, new SecureRandom( ) );
sslfact = (SSLSocketFactory) context.getSocketFactory ();
} catch (KeyManagementException e) {
} catch (NoSuchAlgorithmException e) {
}
sslsocket = (SSLSocket)sslfact.createSocket(address, port);
sslsocket.startHandshake();
in = new Scanner(sslsocket.getInputStream());
out = new PrintStream(sslsocket.getOutputStream());
}
else{
socket = new Socket(address, port);
in = new Scanner(socket.getInputStream());
out = new PrintStream(socket.getOutputStream());
}
readToServerStream();
isConnected = true;
}
catch(Exception e){
IrcBot.out.println("Could not connect: " + e.toString());
IrcBot.out.println("Retrying in 10 seconds");
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
if(!isConnected){
connectTo(address,port,useSSL);
}
}
public static void send(String message){
message = message.replaceAll("\r", "").replaceAll("\n", "");
String[] split = message.split("\\s+");
String tosend = "";
System.out.println();
System.out.println("MESSAGE " + message);
System.out.println();
boolean hitLimit = false;
for(int i = 0;i < split.length;i++){
tosend += split[i] + " ";
if(tosend.length() > 300){
toserver.add(tosend);
hitLimit = true;
String next = split[0] + " " + split[1] + " :";
for(int j = i+1; j < split.length; j++){
next += split[j] + " ";
}
send(next);
break;
}
}
if(!hitLimit)toserver.add(tosend);
}
public static void pm(String target, String message){
send(String.format("PRIVMSG %s :%s", target, message));
}
public static void notice(String target, String message){
send(String.format("NOTICE %s :%s", target, message));
}
public static void lessPrioritySend(String message){
message = message.replaceAll("\r", "").replaceAll("\n", "");
String[] split = message.split("\\s+");
String tosend = "";
boolean hitLimit = false;
for(int i = 0;i < split.length;i++){
tosend += split[i] + " ";
if(tosend.length() > 300){
toserverlesspriority.add(tosend);
hitLimit = true;
String next = split[0] + " " + split[1] + " :";
for(int j = i+1; j < split.length; j++){
next += split[j] + " ";
}
send(next);
break;
}
}
if(!hitLimit)toserverlesspriority.add(tosend);
}
public static void lessPriorityPm(String target, String message){
lessPrioritySend(String.format("PRIVMSG %s :%s", target, message));
}
public static void lessPriorityNotice(String target, String message){
lessPrioritySend(String.format("NOTICE %s :%s", target, message));
}
public static void prioritySend(String message){
message = message.replaceAll("\r", "").replaceAll("\n", "");
String[] split = message.split("\\s+");
String tosend = "";
boolean hitLimit = false;
for(int i = 0;i < split.length;i++){
tosend += split[i] + " ";
if(tosend.length() > 300){
toserver.addFirst(tosend);
hitLimit = true;
String next = split[0] + " " + split[1] + " :";
for(int j = i+1; j < split.length; j++){
next += split[j] + " ";
}
prioritySend(next);
break;
}
}
if(!hitLimit)toserver.addFirst(tosend);
}
public static void priorityPm(String target, String message){
prioritySend(String.format("PRIVMSG %s :%s", target, message));
}
public static void priorityNotice(String target, String message){
prioritySend(String.format("NOTICE %s :%s", target, message));
}
/**
* PRIVMSG for room
* NOTICE for user
*/
public static void say(String target, String message){
if(target.startsWith("#")) Server.pm(target, message);
else Server.notice(target, message);
}
public static void say(String target, String[] messagearray){
for(int i = 0; i < messagearray.length; i++){
if(target.startsWith("#")) Server.pm(target, messagearray[i]);
else Server.notice(target, messagearray[i]);
}
}
/**
* Priority
*/
public static void prioritySay(String target, String message){
if(target.startsWith("#")) Server.priorityPm(target, message);
else Server.priorityNotice(target, message);
}
public static void prioritySay(String target, String[] messagearray){
for(int i = 0; i < messagearray.length; i++){
if(target.startsWith("#")) Server.priorityPm(target, messagearray[i]);
else Server.priorityNotice(target, messagearray[i]);
}
}
/**
* Less Priority say
*/
public static void lessPrioritySay(String target, String message){
if(target.startsWith("#")) Server.lessPriorityPm(target, message);
else Server.lessPriorityNotice(target, message);
}
public static void lessPrioritySay(String target, String[] messagearray){
for(int i = 0; i < messagearray.length; i++){
if(target.startsWith("#")) Server.lessPriorityPm(target, messagearray[i]);
else Server.lessPriorityNotice(target, messagearray[i]);
}
}
public static boolean isConnected(){
return isConnected;
}
public static void resetConnection(String reason){
IrcBot.out.println("Resetting connection: " + reason);
isConnected = false;
IrcBot.stop();
try {
connectTo(address,port,useSSL);
Thread.sleep(2000);
if(IrcBot.attemptLogin()){
IrcBot.sendOnLogin();
isConnected = true;
IrcBot.listenToServer();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void disconnect(){
try {
socket.close();
} catch (IOException e) {
}
System.exit(0);
}
private static void readToServerStream(){
if(reading)return;
reading = true;
thread = new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(1);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
if(toserver.size() != 0){
String tosend = toserver.poll().replaceAll("\r", "").replaceAll("\n", "");;
System.out.println(tosend);
out.println(tosend + "\r\n");
out.flush();
thread.sleep(500);
}
else if(toserverlesspriority.size() != 0){
String tosend = toserverlesspriority.poll().replaceAll("\r", "").replaceAll("\n", "");;
out.println(tosend + "\r\n");
out.flush();
thread.sleep(500);
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
});
thread.start();
}
}
| bot/Server.java | package bot;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Scanner;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class Server {
// Fields
private static SSLSocketFactory sslfact;
public static Scanner in;
public static PrintStream out;
private static Socket socket;
private static SSLSocket sslsocket;
private static boolean isConnected;
private static String address;
private static int port;
private static boolean useSSL;
private static boolean reading = false;
private static ArrayDeque<String> toserver;
private static ArrayDeque<String> toserverlesspriority;
static Thread thread;
public static void connectTo(String address, int port, boolean useSSL){
Server.address = address;
Server.port = port;
Server.useSSL = useSSL;
try{
toserver = new ArrayDeque<String>();
toserverlesspriority = new ArrayDeque<String>();
if(socket != null)socket.close();
if(sslsocket != null)sslsocket.close();
if(out != null) out.close();
if(in != null) in.close();
if(useSSL){
System.setProperty("javax.net.ssl.trustStore", Config.getPathToKeystore());
try {
X509TrustManager[] tm = new X509TrustManager[] { new X509TrustManager(){
public void checkClientTrusted ( X509Certificate[] cert, String authType ) throws CertificateException {
}
public void checkServerTrusted ( X509Certificate[] cert, String authType ) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers (){
return null;
}
}};
SSLContext context = SSLContext.getInstance ("SSL");
context.init( new KeyManager[0], tm, new SecureRandom( ) );
sslfact = (SSLSocketFactory) context.getSocketFactory ();
} catch (KeyManagementException e) {
} catch (NoSuchAlgorithmException e) {
}
sslsocket = (SSLSocket)sslfact.createSocket(address, port);
sslsocket.startHandshake();
in = new Scanner(sslsocket.getInputStream());
out = new PrintStream(sslsocket.getOutputStream());
}
else{
socket = new Socket(address, port);
in = new Scanner(socket.getInputStream());
out = new PrintStream(socket.getOutputStream());
}
readToServerStream();
isConnected = true;
}
catch(Exception e){
IrcBot.out.println("Could not connect: " + e.toString());
IrcBot.out.println("Retrying in 10 seconds");
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
if(!isConnected){
connectTo(address,port,useSSL);
}
}
public static void send(String message){
System.out.println("sending " + message);
toserver.add(message.replaceAll("\r", "").replaceAll("\n", ""));
}
public static void pm(String target, String message){
send(String.format("PRIVMSG %s :%s", target, message));
}
public static void notice(String target, String message){
send(String.format("NOTICE %s :%s", target, message));
}
public static void lessPrioritySend(String message){
//System.out.println("sending " + message);
toserverlesspriority.add(message.replaceAll("\r", "").replaceAll("\n", ""));
}
public static void lessPriorityPm(String target, String message){
lessPrioritySend(String.format("PRIVMSG %s :%s", target, message));
}
public static void lessPriorityNotice(String target, String message){
lessPrioritySend(String.format("NOTICE %s :%s", target, message));
}
public static void prioritySend(String message){
//System.out.println("sending " + message);
toserver.addFirst(message.replaceAll("\r", "").replaceAll("\n", ""));
}
public static void priorityPm(String target, String message){
prioritySend(String.format("PRIVMSG %s :%s", target, message));
}
public static void priorityNotice(String target, String message){
prioritySend(String.format("NOTICE %s :%s", target, message));
}
/**
* PRIVMSG for room
* NOTICE for user
*/
public static void say(String target, String message){
if(target.startsWith("#")) Server.pm(target, message);
else Server.notice(target, message);
}
public static void say(String target, String[] messagearray){
for(int i = 0; i < messagearray.length; i++){
if(target.startsWith("#")) Server.pm(target, messagearray[i]);
else Server.notice(target, messagearray[i]);
}
}
/**
* Priority
*/
public static void prioritySay(String target, String message){
if(target.startsWith("#")) Server.priorityPm(target, message);
else Server.priorityNotice(target, message);
}
public static void prioritySay(String target, String[] messagearray){
for(int i = 0; i < messagearray.length; i++){
if(target.startsWith("#")) Server.priorityPm(target, messagearray[i]);
else Server.priorityNotice(target, messagearray[i]);
}
}
/**
* Less Priority say
*/
public static void lessPrioritySay(String target, String message){
if(target.startsWith("#")) Server.lessPriorityPm(target, message);
else Server.lessPriorityNotice(target, message);
}
public static void lessPrioritySay(String target, String[] messagearray){
for(int i = 0; i < messagearray.length; i++){
if(target.startsWith("#")) Server.lessPriorityPm(target, messagearray[i]);
else Server.lessPriorityNotice(target, messagearray[i]);
}
}
public static boolean isConnected(){
return isConnected;
}
public static void resetConnection(String reason){
IrcBot.out.println("Resetting connection: " + reason);
isConnected = false;
IrcBot.stop();
try {
connectTo(address,port,useSSL);
Thread.sleep(2000);
if(IrcBot.attemptLogin()){
IrcBot.sendOnLogin();
isConnected = true;
IrcBot.listenToServer();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void disconnect(){
try {
socket.close();
} catch (IOException e) {
}
System.exit(0);
}
private static void readToServerStream(){
if(reading)return;
reading = true;
thread = new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(1);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
if(toserver.size() != 0){
String tosend = toserver.poll().replaceAll("\r", "").replaceAll("\n", "");;
System.out.println(tosend);
out.println(tosend + "\r\n");
out.flush();
thread.sleep(500);
}
else if(toserverlesspriority.size() != 0){
String tosend = toserverlesspriority.poll().replaceAll("\r", "").replaceAll("\n", "");;
out.println(tosend + "\r\n");
out.flush();
thread.sleep(500);
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
});
thread.start();
}
}
| Split messages down to 300 chars each
| bot/Server.java | Split messages down to 300 chars each | <ide><path>ot/Server.java
<ide> }
<ide>
<ide> public static void send(String message){
<del> System.out.println("sending " + message);
<del> toserver.add(message.replaceAll("\r", "").replaceAll("\n", ""));
<add> message = message.replaceAll("\r", "").replaceAll("\n", "");
<add> String[] split = message.split("\\s+");
<add> String tosend = "";
<add> System.out.println();
<add> System.out.println("MESSAGE " + message);
<add> System.out.println();
<add> boolean hitLimit = false;
<add> for(int i = 0;i < split.length;i++){
<add> tosend += split[i] + " ";
<add> if(tosend.length() > 300){
<add> toserver.add(tosend);
<add> hitLimit = true;
<add> String next = split[0] + " " + split[1] + " :";
<add> for(int j = i+1; j < split.length; j++){
<add> next += split[j] + " ";
<add> }
<add> send(next);
<add> break;
<add> }
<add> }
<add> if(!hitLimit)toserver.add(tosend);
<ide> }
<ide>
<ide> public static void pm(String target, String message){
<ide> }
<ide>
<ide> public static void lessPrioritySend(String message){
<del> //System.out.println("sending " + message);
<del> toserverlesspriority.add(message.replaceAll("\r", "").replaceAll("\n", ""));
<add> message = message.replaceAll("\r", "").replaceAll("\n", "");
<add> String[] split = message.split("\\s+");
<add> String tosend = "";
<add> boolean hitLimit = false;
<add> for(int i = 0;i < split.length;i++){
<add> tosend += split[i] + " ";
<add> if(tosend.length() > 300){
<add> toserverlesspriority.add(tosend);
<add> hitLimit = true;
<add> String next = split[0] + " " + split[1] + " :";
<add> for(int j = i+1; j < split.length; j++){
<add> next += split[j] + " ";
<add> }
<add> send(next);
<add> break;
<add> }
<add> }
<add> if(!hitLimit)toserverlesspriority.add(tosend);
<ide> }
<ide>
<ide> public static void lessPriorityPm(String target, String message){
<ide> }
<ide>
<ide> public static void prioritySend(String message){
<del> //System.out.println("sending " + message);
<del> toserver.addFirst(message.replaceAll("\r", "").replaceAll("\n", ""));
<add> message = message.replaceAll("\r", "").replaceAll("\n", "");
<add> String[] split = message.split("\\s+");
<add> String tosend = "";
<add> boolean hitLimit = false;
<add> for(int i = 0;i < split.length;i++){
<add> tosend += split[i] + " ";
<add> if(tosend.length() > 300){
<add> toserver.addFirst(tosend);
<add> hitLimit = true;
<add> String next = split[0] + " " + split[1] + " :";
<add> for(int j = i+1; j < split.length; j++){
<add> next += split[j] + " ";
<add> }
<add> prioritySend(next);
<add> break;
<add> }
<add> }
<add> if(!hitLimit)toserver.addFirst(tosend);
<add>
<add>
<ide> }
<ide>
<ide> public static void priorityPm(String target, String message){ |
|
Java | agpl-3.0 | 1416ad7208d1b0d13bb434945402dd745c84ff67 | 0 | mvdstruijk/flamingo,mvdstruijk/flamingo,B3Partners/flamingo,mvdstruijk/flamingo,flamingo-geocms/flamingo,B3Partners/flamingo,flamingo-geocms/flamingo,mvdstruijk/flamingo,flamingo-geocms/flamingo,flamingo-geocms/flamingo,B3Partners/flamingo,B3Partners/flamingo | /*
* Copyright (C) 2011 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.viewer.config.app;
import nl.b3p.viewer.config.ClobElement;
import java.util.*;
import javax.persistence.*;
import javax.servlet.http.HttpServletRequest;
import nl.b3p.viewer.config.security.Authorizations;
import nl.b3p.viewer.config.security.User;
import nl.b3p.viewer.config.services.BoundingBox;
import nl.b3p.viewer.config.services.GeoService;
import org.apache.commons.beanutils.BeanUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Matthijs Laan
*/
@Entity
@Table(
uniqueConstraints=
@UniqueConstraint(columnNames={"name", "version"})
)
public class Application {
public static final String DETAIL_LAST_SPINUP_TIME = "lastSpinupTime";
private static Set adminOnlyDetails = new HashSet<String>(Arrays.asList(new String[] {
"opmerking"
}));
@Id
private Long id;
@Basic(optional=false)
private String name;
@Column(length=30)
private String version;
@Lob
@org.hibernate.annotations.Type(type="org.hibernate.type.StringClobType")
private String layout;
@ElementCollection
@JoinTable(joinColumns=@JoinColumn(name="application"))
// Element wrapper required because of http://opensource.atlassian.com/projects/hibernate/browse/JPA-11
private Map<String,ClobElement> details = new HashMap<String,ClobElement>();
@ManyToOne
private User owner;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "crs.name", column = @Column(name="start_crs")),
@AttributeOverride(name = "minx", column = @Column(name="start_minx")),
@AttributeOverride(name = "maxx", column = @Column(name="start_maxx")),
@AttributeOverride(name = "miny", column = @Column(name="start_miny")),
@AttributeOverride(name = "maxy", column = @Column(name="start_maxy"))
})
private BoundingBox startExtent;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "crs.name", column = @Column(name="max_crs")),
@AttributeOverride(name = "minx", column = @Column(name="max_minx")),
@AttributeOverride(name = "maxx", column = @Column(name="max_maxx")),
@AttributeOverride(name = "miny", column = @Column(name="max_miny")),
@AttributeOverride(name = "maxy", column = @Column(name="max_maxy"))
})
private BoundingBox maxExtent;
private boolean authenticatedRequired ;
@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private Level root;
@OneToMany(orphanRemoval=true, cascade=CascadeType.ALL, mappedBy="application")
private Set<ConfiguredComponent> components = new HashSet<ConfiguredComponent>();
@Basic(optional=false)
@Temporal(TemporalType.TIMESTAMP)
private Date authorizationsModified = new Date();
// <editor-fold defaultstate="collapsed" desc="getters and setters">
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getLayout() {
return layout;
}
public void setLayout(String layout) {
this.layout = layout;
}
public Map<String, ClobElement> getDetails() {
return details;
}
public void setDetails(Map<String, ClobElement> details) {
this.details = details;
}
public boolean isAuthenticatedRequired() {
return authenticatedRequired;
}
public void setAuthenticatedRequired(boolean authenticatedRequired) {
this.authenticatedRequired = authenticatedRequired;
}
public Set<ConfiguredComponent> getComponents() {
return components;
}
public void setComponents(Set<ConfiguredComponent> components) {
this.components = components;
}
public BoundingBox getMaxExtent() {
return maxExtent;
}
public void setMaxExtent(BoundingBox maxExtent) {
this.maxExtent = maxExtent;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
public Level getRoot() {
return root;
}
public void setRoot(Level root) {
this.root = root;
}
public BoundingBox getStartExtent() {
return startExtent;
}
public void setStartExtent(BoundingBox startExtent) {
this.startExtent = startExtent;
}
public Date getAuthorizationsModified() {
return authorizationsModified;
}
public void setAuthorizationsModified(Date authorizationsModified) {
this.authorizationsModified = authorizationsModified;
}
//</editor-fold>
public String getNameWithVersion() {
String n = getName();
if(getVersion() != null) {
n += " v" + getVersion();
}
return n;
}
public static class TreeCache {
List<Level> levels;
Map<Level,List<Level>> childrenByParent;
List<ApplicationLayer> applicationLayers;
public List<ApplicationLayer> getApplicationLayers() {
return applicationLayers;
}
public List<Level> getChildren(Level l) {
List<Level> children = childrenByParent.get(l);
if(children == null) {
return Collections.EMPTY_LIST;
} else {
return children;
}
}
public List<Level> getLevels() {
return levels;
}
}
@Transient
private TreeCache treeCache;
public TreeCache loadTreeCache() {
if(treeCache == null) {
treeCache = new TreeCache();
// Retrieve level tree structure in single query
treeCache.levels = Stripersist.getEntityManager().createNamedQuery("getLevelTree")
.setParameter("rootId", root.getId())
.getResultList();
// Prevent n+1 queries for each level
Stripersist.getEntityManager().createQuery("from Level l "
+ "left join fetch l.layers "
+ "where l in (:levels) ")
.setParameter("levels", treeCache.levels)
.getResultList();
treeCache.childrenByParent = new HashMap();
treeCache.applicationLayers = new ArrayList();
for(Level l: treeCache.levels) {
treeCache.applicationLayers.addAll(l.getLayers());
if(l.getParent() != null) {
List<Level> parentChildren = treeCache.childrenByParent.get(l.getParent());
if(parentChildren == null) {
parentChildren = new ArrayList<Level>();
treeCache.childrenByParent.put(l.getParent(), parentChildren);
}
parentChildren.add(l);
}
}
}
return treeCache;
}
public void authorizationsModified() {
authorizationsModified = new Date();
}
/**
* Create a JSON representation for use in browser to start this application
* @return
*/
public String toJSON(HttpServletRequest request) throws JSONException {
JSONObject o = new JSONObject();
o.put("id", id);
o.put("name", name);
if(layout != null) {
o.put("layout", new JSONObject(layout));
}
JSONObject d = new JSONObject();
o.put("details", d);
for(Map.Entry<String,ClobElement> e: details.entrySet()) {
if(!adminOnlyDetails.contains(e.getKey())) {
d.put(e.getKey(), e.getValue());
}
}
if(startExtent != null) {
o.put("startExtent", startExtent.toJSONObject());
}
if(maxExtent != null) {
o.put("maxExtent", maxExtent.toJSONObject());
}
/* TODO check readers */
if(root != null) {
o.put("rootLevel", root.getId().toString());
loadTreeCache();
// Prevent n+1 queries for each level
Stripersist.getEntityManager().createQuery("from Level l "
+ "left join fetch l.documents "
+ "where l in (:levels) ")
.setParameter("levels", treeCache.levels)
.getResultList();
if(!treeCache.applicationLayers.isEmpty()) {
// Prevent n+1 queries for each ApplicationLayer
Stripersist.getEntityManager().createQuery("from ApplicationLayer al "
+ "left join fetch al.details "
+ "where al in (:alayers) ")
.setParameter("alayers", treeCache.applicationLayers)
.getResultList();
}
JSONObject levels = new JSONObject();
o.put("levels", levels);
JSONObject appLayers = new JSONObject();
o.put("appLayers", appLayers);
JSONArray selectedContent = new JSONArray();
o.put("selectedContent", selectedContent);
List selectedObjects = new ArrayList();
walkAppTreeForJSON(levels, appLayers, selectedObjects, root, false, request);
Collections.sort(selectedObjects, new Comparator() {
@Override
public int compare(Object lhs, Object rhs) {
Integer lhsIndex, rhsIndex;
if(lhs instanceof Level) {
lhsIndex = ((Level)lhs).getSelectedIndex();
} else {
lhsIndex = ((ApplicationLayer)lhs).getSelectedIndex();
}
if(rhs instanceof Level) {
rhsIndex = ((Level)rhs).getSelectedIndex();
} else {
rhsIndex = ((ApplicationLayer)rhs).getSelectedIndex();
}
return lhsIndex.compareTo(rhsIndex);
}
});
for(Object obj: selectedObjects) {
JSONObject j = new JSONObject();
if(obj instanceof Level) {
j.put("type", "level");
j.put("id", ((Level)obj).getId().toString());
} else {
j.put("type", "appLayer");
j.put("id", ((ApplicationLayer)obj).getId().toString());
}
selectedContent.put(j);
}
Map<GeoService,Set<String>> usedLayersByService = new HashMap<GeoService,Set<String>>();
visitLevelForUsedServicesLayers(root, usedLayersByService, request);
if(!usedLayersByService.isEmpty()) {
JSONObject services = new JSONObject();
o.put("services", services);
for(Map.Entry<GeoService,Set<String>> entry: usedLayersByService.entrySet()) {
GeoService gs = entry.getKey();
Set<String> usedLayers = entry.getValue();
services.put(gs.getId().toString(), gs.toJSONObject(false, usedLayers));
}
}
}
// Prevent n+1 query for ConfiguredComponent.details
Stripersist.getEntityManager().createQuery(
"from ConfiguredComponent cc left join fetch cc.details where application = :this")
.setParameter("this", this)
.getResultList();
JSONObject c = new JSONObject();
o.put("components", c);
for(ConfiguredComponent comp: components) {
if(Authorizations.isConfiguredComponentAuthorized(comp, request)) {
c.put(comp.getName(), comp.toJSON());
}
}
return o.toString(4);
}
private void walkAppTreeForJSON(JSONObject levels, JSONObject appLayers, List selectedContent, Level l, boolean parentIsBackground, HttpServletRequest request) throws JSONException {
JSONObject o = l.toJSONObject(false, this, request);
o.put("background", l.isBackground() || parentIsBackground);
levels.put(l.getId().toString(), o);
if(l.getSelectedIndex() != null) {
selectedContent.add(l);
}
for(ApplicationLayer al: l.getLayers()) {
if(!Authorizations.isAppLayerReadAuthorized(this, al, request)) {
//System.out.printf("Application layer %d (service #%s %s layer %s) in level %d %s unauthorized\n", al.getId(), al.getService().getId(), al.getService().getName(), al.getLayerName(), l.getId(), l.getName());
continue;
}
JSONObject p = al.toJSONObject();
p.put("background", l.isBackground() || parentIsBackground);
p.put("editAuthorized", Authorizations.isAppLayerWriteAuthorized(this, al, request));
appLayers.put(al.getId().toString(), p);
if(al.getSelectedIndex() != null) {
selectedContent.add(al);
}
}
List<Level> children = treeCache.childrenByParent.get(l);
if(children != null) {
JSONArray jsonChildren = new JSONArray();
o.put("children", jsonChildren);
for(Level child: children) {
if (Authorizations.isLevelReadAuthorized(this, child, request)){
jsonChildren.put(child.getId().toString());
walkAppTreeForJSON(levels, appLayers, selectedContent, child, l.isBackground(), request);
}
}
}
}
private void visitLevelForUsedServicesLayers(Level l, Map<GeoService,Set<String>> usedLayersByService, HttpServletRequest request) {
if(!Authorizations.isLevelReadAuthorized(this, l, request)) {
return;
}
for(ApplicationLayer al: l.getLayers()) {
if(!Authorizations.isAppLayerReadAuthorized(this, al, request)) {
continue;
}
GeoService gs = al.getService();
Set<String> usedLayers = usedLayersByService.get(gs);
if(usedLayers == null) {
usedLayers = new HashSet<String>();
usedLayersByService.put(gs, usedLayers);
}
usedLayers.add(al.getLayerName());
}
List<Level> children = treeCache.childrenByParent.get(l);
if(children != null) {
for(Level child: children) {
visitLevelForUsedServicesLayers(child, usedLayersByService, request);
}
}
}
public Boolean isMashup(){
if(this.getDetails().containsKey("isMashup")){
String mashupValue = this.getDetails().get("isMashup").getValue();
Boolean mashup = Boolean.valueOf(mashupValue);
return mashup;
}else{
return false;
}
}
public Application deepCopy() throws Exception {
Application copy = (Application) BeanUtils.cloneBean(this);
copy.setId(null);
// user reference is not deep copied, of course
copy.setDetails(new HashMap<String,ClobElement>(details));
if(startExtent != null) {
copy.setStartExtent(startExtent.clone());
}
if(maxExtent != null) {
copy.setMaxExtent(maxExtent.clone());
}
copy.setComponents(new HashSet<ConfiguredComponent>());
for(ConfiguredComponent cc: components) {
copy.getComponents().add(cc.deepCopy(copy));
}
if(root != null) {
copy.setRoot(root.deepCopy(null));
}
return copy;
}
public void setMaxWidth(String maxWidth) {
this.details.put("maxWidth", new ClobElement(maxWidth));
}
public void setMaxHeight(String maxHeight) {
this.details.put("maxHeight", new ClobElement(maxHeight));
}
}
| src/nl/b3p/viewer/config/app/Application.java | /*
* Copyright (C) 2011 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.viewer.config.app;
import nl.b3p.viewer.config.ClobElement;
import java.util.*;
import javax.persistence.*;
import javax.servlet.http.HttpServletRequest;
import nl.b3p.viewer.config.security.Authorizations;
import nl.b3p.viewer.config.security.User;
import nl.b3p.viewer.config.services.BoundingBox;
import nl.b3p.viewer.config.services.GeoService;
import org.apache.commons.beanutils.BeanUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Matthijs Laan
*/
@Entity
@Table(
uniqueConstraints=
@UniqueConstraint(columnNames={"name", "version"})
)
public class Application {
public static final String DETAIL_LAST_SPINUP_TIME = "lastSpinupTime";
private static Set adminOnlyDetails = new HashSet<String>(Arrays.asList(new String[] {
"opmerking"
}));
@Id
private Long id;
@Basic(optional=false)
private String name;
@Column(length=30)
private String version;
@Lob
@org.hibernate.annotations.Type(type="org.hibernate.type.StringClobType")
private String layout;
@ElementCollection
@JoinTable(joinColumns=@JoinColumn(name="application"))
// Element wrapper required because of http://opensource.atlassian.com/projects/hibernate/browse/JPA-11
private Map<String,ClobElement> details = new HashMap<String,ClobElement>();
@ManyToOne
private User owner;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "crs.name", column = @Column(name="start_crs")),
@AttributeOverride(name = "minx", column = @Column(name="start_minx")),
@AttributeOverride(name = "maxx", column = @Column(name="start_maxx")),
@AttributeOverride(name = "miny", column = @Column(name="start_miny")),
@AttributeOverride(name = "maxy", column = @Column(name="start_maxy"))
})
private BoundingBox startExtent;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "crs.name", column = @Column(name="max_crs")),
@AttributeOverride(name = "minx", column = @Column(name="max_minx")),
@AttributeOverride(name = "maxx", column = @Column(name="max_maxx")),
@AttributeOverride(name = "miny", column = @Column(name="max_miny")),
@AttributeOverride(name = "maxy", column = @Column(name="max_maxy"))
})
private BoundingBox maxExtent;
private boolean authenticatedRequired ;
@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private Level root;
@OneToMany(orphanRemoval=true, cascade=CascadeType.ALL, mappedBy="application")
private Set<ConfiguredComponent> components = new HashSet<ConfiguredComponent>();
@Basic(optional=false)
@Temporal(TemporalType.TIMESTAMP)
private Date authorizationsModified = new Date();
// <editor-fold defaultstate="collapsed" desc="getters and setters">
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getLayout() {
return layout;
}
public void setLayout(String layout) {
this.layout = layout;
}
public Map<String, ClobElement> getDetails() {
return details;
}
public void setDetails(Map<String, ClobElement> details) {
this.details = details;
}
public boolean isAuthenticatedRequired() {
return authenticatedRequired;
}
public void setAuthenticatedRequired(boolean authenticatedRequired) {
this.authenticatedRequired = authenticatedRequired;
}
public Set<ConfiguredComponent> getComponents() {
return components;
}
public void setComponents(Set<ConfiguredComponent> components) {
this.components = components;
}
public BoundingBox getMaxExtent() {
return maxExtent;
}
public void setMaxExtent(BoundingBox maxExtent) {
this.maxExtent = maxExtent;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
public Level getRoot() {
return root;
}
public void setRoot(Level root) {
this.root = root;
}
public BoundingBox getStartExtent() {
return startExtent;
}
public void setStartExtent(BoundingBox startExtent) {
this.startExtent = startExtent;
}
public Date getAuthorizationsModified() {
return authorizationsModified;
}
public void setAuthorizationsModified(Date authorizationsModified) {
this.authorizationsModified = authorizationsModified;
}
//</editor-fold>
public String getNameWithVersion() {
String n = getName();
if(getVersion() != null) {
n += " v" + getVersion();
}
return n;
}
public static class TreeCache {
List<Level> levels;
Map<Level,List<Level>> childrenByParent;
List<ApplicationLayer> applicationLayers;
public List<ApplicationLayer> getApplicationLayers() {
return applicationLayers;
}
public List<Level> getChildren(Level l) {
List<Level> children = childrenByParent.get(l);
if(children == null) {
return Collections.EMPTY_LIST;
} else {
return children;
}
}
public List<Level> getLevels() {
return levels;
}
}
@Transient
private TreeCache treeCache;
public TreeCache loadTreeCache() {
if(treeCache == null) {
treeCache = new TreeCache();
// Retrieve level tree structure in single query
treeCache.levels = Stripersist.getEntityManager().createNamedQuery("getLevelTree")
.setParameter("rootId", root.getId())
.getResultList();
// Prevent n+1 queries for each level
Stripersist.getEntityManager().createQuery("from Level l "
+ "left join fetch l.layers "
+ "where l in (:levels) ")
.setParameter("levels", treeCache.levels)
.getResultList();
treeCache.childrenByParent = new HashMap();
treeCache.applicationLayers = new ArrayList();
for(Level l: treeCache.levels) {
treeCache.applicationLayers.addAll(l.getLayers());
if(l.getParent() != null) {
List<Level> parentChildren = treeCache.childrenByParent.get(l.getParent());
if(parentChildren == null) {
parentChildren = new ArrayList<Level>();
treeCache.childrenByParent.put(l.getParent(), parentChildren);
}
parentChildren.add(l);
}
}
}
return treeCache;
}
public void authorizationsModified() {
authorizationsModified = new Date();
}
/**
* Create a JSON representation for use in browser to start this application
* @return
*/
public String toJSON(HttpServletRequest request) throws JSONException {
JSONObject o = new JSONObject();
o.put("id", id);
o.put("name", name);
if(layout != null) {
o.put("layout", new JSONObject(layout));
}
JSONObject d = new JSONObject();
o.put("details", d);
for(Map.Entry<String,ClobElement> e: details.entrySet()) {
if(!adminOnlyDetails.contains(e.getKey())) {
d.put(e.getKey(), e.getValue());
}
}
if(startExtent != null) {
o.put("startExtent", startExtent.toJSONObject());
}
if(maxExtent != null) {
o.put("maxExtent", maxExtent.toJSONObject());
}
/* TODO check readers */
if(root != null) {
o.put("rootLevel", root.getId().toString());
loadTreeCache();
// Prevent n+1 queries for each level
Stripersist.getEntityManager().createQuery("from Level l "
+ "left join fetch l.documents "
+ "where l in (:levels) ")
.setParameter("levels", treeCache.levels)
.getResultList();
if(!treeCache.applicationLayers.isEmpty()) {
// Prevent n+1 queries for each ApplicationLayer
Stripersist.getEntityManager().createQuery("from ApplicationLayer al "
+ "left join fetch al.details "
+ "where al in (:alayers) ")
.setParameter("alayers", treeCache.applicationLayers)
.getResultList();
}
JSONObject levels = new JSONObject();
o.put("levels", levels);
JSONObject appLayers = new JSONObject();
o.put("appLayers", appLayers);
JSONArray selectedContent = new JSONArray();
o.put("selectedContent", selectedContent);
List selectedObjects = new ArrayList();
walkAppTreeForJSON(levels, appLayers, selectedObjects, root, false, request);
Collections.sort(selectedObjects, new Comparator() {
@Override
public int compare(Object lhs, Object rhs) {
Integer lhsIndex, rhsIndex;
if(lhs instanceof Level) {
lhsIndex = ((Level)lhs).getSelectedIndex();
} else {
lhsIndex = ((ApplicationLayer)lhs).getSelectedIndex();
}
if(rhs instanceof Level) {
rhsIndex = ((Level)rhs).getSelectedIndex();
} else {
rhsIndex = ((ApplicationLayer)rhs).getSelectedIndex();
}
return lhsIndex.compareTo(rhsIndex);
}
});
for(Object obj: selectedObjects) {
JSONObject j = new JSONObject();
if(obj instanceof Level) {
j.put("type", "level");
j.put("id", ((Level)obj).getId().toString());
} else {
j.put("type", "appLayer");
j.put("id", ((ApplicationLayer)obj).getId().toString());
}
selectedContent.put(j);
}
Map<GeoService,Set<String>> usedLayersByService = new HashMap<GeoService,Set<String>>();
visitLevelForUsedServicesLayers(root, usedLayersByService, request);
if(!usedLayersByService.isEmpty()) {
JSONObject services = new JSONObject();
o.put("services", services);
for(Map.Entry<GeoService,Set<String>> entry: usedLayersByService.entrySet()) {
GeoService gs = entry.getKey();
Set<String> usedLayers = entry.getValue();
services.put(gs.getId().toString(), gs.toJSONObject(false, usedLayers));
}
}
}
// Prevent n+1 query for ConfiguredComponent.details
Stripersist.getEntityManager().createQuery(
"from ConfiguredComponent cc left join fetch cc.details where application = :this")
.setParameter("this", this)
.getResultList();
JSONObject c = new JSONObject();
o.put("components", c);
for(ConfiguredComponent comp: components) {
if(Authorizations.isConfiguredComponentAuthorized(comp, request)) {
c.put(comp.getName(), comp.toJSON());
}
}
return o.toString(4);
}
private void walkAppTreeForJSON(JSONObject levels, JSONObject appLayers, List selectedContent, Level l, boolean parentIsBackground, HttpServletRequest request) throws JSONException {
if(!Authorizations.isLevelReadAuthorized(this, l, request)) {
//System.out.printf("Level %d %s unauthorized\n", l.getId(), l.getName());
return;
}
JSONObject o = l.toJSONObject(false, this, request);
o.put("background", l.isBackground() || parentIsBackground);
levels.put(l.getId().toString(), o);
if(l.getSelectedIndex() != null) {
selectedContent.add(l);
}
for(ApplicationLayer al: l.getLayers()) {
if(!Authorizations.isAppLayerReadAuthorized(this, al, request)) {
//System.out.printf("Application layer %d (service #%s %s layer %s) in level %d %s unauthorized\n", al.getId(), al.getService().getId(), al.getService().getName(), al.getLayerName(), l.getId(), l.getName());
continue;
}
JSONObject p = al.toJSONObject();
p.put("background", l.isBackground() || parentIsBackground);
p.put("editAuthorized", Authorizations.isAppLayerWriteAuthorized(this, al, request));
appLayers.put(al.getId().toString(), p);
if(al.getSelectedIndex() != null) {
selectedContent.add(al);
}
}
List<Level> children = treeCache.childrenByParent.get(l);
if(children != null) {
JSONArray jsonChildren = new JSONArray();
o.put("children", jsonChildren);
for(Level child: children) {
jsonChildren.put(child.getId().toString());
walkAppTreeForJSON(levels, appLayers, selectedContent, child, l.isBackground(), request);
}
}
}
private void visitLevelForUsedServicesLayers(Level l, Map<GeoService,Set<String>> usedLayersByService, HttpServletRequest request) {
if(!Authorizations.isLevelReadAuthorized(this, l, request)) {
return;
}
for(ApplicationLayer al: l.getLayers()) {
if(!Authorizations.isAppLayerReadAuthorized(this, al, request)) {
continue;
}
GeoService gs = al.getService();
Set<String> usedLayers = usedLayersByService.get(gs);
if(usedLayers == null) {
usedLayers = new HashSet<String>();
usedLayersByService.put(gs, usedLayers);
}
usedLayers.add(al.getLayerName());
}
List<Level> children = treeCache.childrenByParent.get(l);
if(children != null) {
for(Level child: children) {
visitLevelForUsedServicesLayers(child, usedLayersByService, request);
}
}
}
public Boolean isMashup(){
if(this.getDetails().containsKey("isMashup")){
String mashupValue = this.getDetails().get("isMashup").getValue();
Boolean mashup = Boolean.valueOf(mashupValue);
return mashup;
}else{
return false;
}
}
public Application deepCopy() throws Exception {
Application copy = (Application) BeanUtils.cloneBean(this);
copy.setId(null);
// user reference is not deep copied, of course
copy.setDetails(new HashMap<String,ClobElement>(details));
if(startExtent != null) {
copy.setStartExtent(startExtent.clone());
}
if(maxExtent != null) {
copy.setMaxExtent(maxExtent.clone());
}
copy.setComponents(new HashSet<ConfiguredComponent>());
for(ConfiguredComponent cc: components) {
copy.getComponents().add(cc.deepCopy(copy));
}
if(root != null) {
copy.setRoot(root.deepCopy(null));
}
return copy;
}
public void setMaxWidth(String maxWidth) {
this.details.put("maxWidth", new ClobElement(maxWidth));
}
public void setMaxHeight(String maxHeight) {
this.details.put("maxHeight", new ClobElement(maxHeight));
}
}
| check for level authorization before adding the id as a child.
| src/nl/b3p/viewer/config/app/Application.java | check for level authorization before adding the id as a child. | <ide><path>rc/nl/b3p/viewer/config/app/Application.java
<ide> }
<ide>
<ide> private void walkAppTreeForJSON(JSONObject levels, JSONObject appLayers, List selectedContent, Level l, boolean parentIsBackground, HttpServletRequest request) throws JSONException {
<del> if(!Authorizations.isLevelReadAuthorized(this, l, request)) {
<del> //System.out.printf("Level %d %s unauthorized\n", l.getId(), l.getName());
<del> return;
<del> }
<ide> JSONObject o = l.toJSONObject(false, this, request);
<ide> o.put("background", l.isBackground() || parentIsBackground);
<ide> levels.put(l.getId().toString(), o);
<ide> JSONArray jsonChildren = new JSONArray();
<ide> o.put("children", jsonChildren);
<ide> for(Level child: children) {
<del> jsonChildren.put(child.getId().toString());
<del> walkAppTreeForJSON(levels, appLayers, selectedContent, child, l.isBackground(), request);
<add> if (Authorizations.isLevelReadAuthorized(this, child, request)){
<add> jsonChildren.put(child.getId().toString());
<add> walkAppTreeForJSON(levels, appLayers, selectedContent, child, l.isBackground(), request);
<add> }
<ide> }
<ide> }
<ide> } |
|
Java | bsd-3-clause | c2ac76462a96c35af27edfc21648386a3beff2e1 | 0 | versionone/VersionOne.Integration.IntelliJ-IDEA,versionone/VersionOne.Integration.IntelliJ-IDEA | /*(c) Copyright 2010, VersionOne, Inc. All rights reserved. (c)*/
package com.versionone.integration.idea;
import com.intellij.openapi.editor.colors.ColorKey;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.versionone.common.sdk.Workitem;
import com.versionone.common.sdk.EntityType;
import com.intellij.openapi.util.IconLoader;
import javax.swing.*;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
import java.util.Map;
import java.util.HashMap;
/**
* Renderer for workitems in tree.
*/
public class WorkItemTreeTableCellRenderer extends DefaultTreeCellRenderer {
private final Map<EntityType, Icon> icons;
private final EditorColorsScheme colorsScheme = EditorColorsManager.getInstance().getGlobalScheme();
private final Color defaultForeColor = getForeground();
public WorkItemTreeTableCellRenderer() {
icons = new HashMap<EntityType, Icon>();
icons.put(EntityType.Defect, IconLoader.getIcon("/defect.gif"));
icons.put(EntityType.Story, IconLoader.getIcon("/story.gif"));
icons.put(EntityType.Test, IconLoader.getIcon("/test.gif"));
icons.put(EntityType.Task, IconLoader.getIcon("/task.gif"));
}
/**
* Sets specify icon for tree.
*
* @param icon - icon for nodes.
*/
private void setWorkitemIcon(Icon icon) {
setIcon(icon);
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel,
boolean expanded,
boolean leaf, int row,
boolean hasFocus) {
Object newValue = "root";
if (value instanceof Workitem) {
Workitem item = (Workitem) value;
newValue = item.getProperty("Name");
setWorkitemIcon(icons.get(item.getType()));
if (item.hasChanges()) {
setBackgroundNonSelectionColor(colorsScheme.getColor(ColorKey.find("V1_CHANGED_ROW")));
setForeground(Color.black);
} else {
setBackgroundNonSelectionColor(getBackground());
setForeground(defaultForeColor);
}
}
return super.getTreeCellRendererComponent(tree, newValue, sel, expanded, leaf, row, hasFocus);
}
}
| src/com/versionone/integration/idea/WorkItemTreeTableCellRenderer.java | /*(c) Copyright 2010, VersionOne, Inc. All rights reserved. (c)*/
package com.versionone.integration.idea;
import com.intellij.openapi.editor.colors.ColorKey;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.versionone.common.sdk.Workitem;
import com.versionone.common.sdk.EntityType;
import com.intellij.openapi.util.IconLoader;
import javax.swing.*;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
import java.util.Map;
import java.util.HashMap;
/**
* Renderer for workitems in tree.
*/
public class WorkItemTreeTableCellRenderer extends DefaultTreeCellRenderer {
private final Map<EntityType, Icon> icons;
private final EditorColorsScheme colorsScheme = EditorColorsManager.getInstance().getGlobalScheme();
private final Color defaultForeColor = getForeground();
public WorkItemTreeTableCellRenderer() {
icons = new HashMap<EntityType, Icon>();
icons.put(EntityType.Defect, IconLoader.getIcon("/defect.gif"));
icons.put(EntityType.Story, IconLoader.getIcon("/story.gif"));
icons.put(EntityType.Test, IconLoader.getIcon("/test.gif"));
icons.put(EntityType.Task, IconLoader.getIcon("/task.gif"));
}
/**
* Sets specify icon for tree.
*
* @param icon - icon for nodes.
*/
private void setWorkitemIcon(Icon icon) {
setIcon(icon);
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel,
boolean expanded,
boolean leaf, int row,
boolean hasFocus) {
Workitem item = (Workitem) value;
Object newValue = item.getProperty("Name");
setWorkitemIcon(icons.get(item.getType()));
if (item.hasChanges()) {
setBackgroundNonSelectionColor(colorsScheme.getColor(ColorKey.find("V1_CHANGED_ROW")));
setForeground(Color.black);
} else {
setBackgroundNonSelectionColor(getBackground());
setForeground(defaultForeColor);
}
return super.getTreeCellRendererComponent(tree, newValue, sel, expanded, leaf, row, hasFocus);
}
}
| fix: renderer would fail on Root element which is not Workitem but String
git-svn-id: 0e61b79a83f52b3fac5942690d0212c33487ecd7@36783 542498e7-56f8-f544-a0f2-a85913ac812a
| src/com/versionone/integration/idea/WorkItemTreeTableCellRenderer.java | fix: renderer would fail on Root element which is not Workitem but String | <ide><path>rc/com/versionone/integration/idea/WorkItemTreeTableCellRenderer.java
<ide> boolean leaf, int row,
<ide> boolean hasFocus) {
<ide>
<del> Workitem item = (Workitem) value;
<add> Object newValue = "root";
<ide>
<del> Object newValue = item.getProperty("Name");
<del> setWorkitemIcon(icons.get(item.getType()));
<add> if (value instanceof Workitem) {
<add> Workitem item = (Workitem) value;
<ide>
<del> if (item.hasChanges()) {
<del> setBackgroundNonSelectionColor(colorsScheme.getColor(ColorKey.find("V1_CHANGED_ROW")));
<del> setForeground(Color.black);
<del> } else {
<del> setBackgroundNonSelectionColor(getBackground());
<del> setForeground(defaultForeColor);
<add> newValue = item.getProperty("Name");
<add> setWorkitemIcon(icons.get(item.getType()));
<add>
<add> if (item.hasChanges()) {
<add> setBackgroundNonSelectionColor(colorsScheme.getColor(ColorKey.find("V1_CHANGED_ROW")));
<add> setForeground(Color.black);
<add> } else {
<add> setBackgroundNonSelectionColor(getBackground());
<add> setForeground(defaultForeColor);
<add> }
<ide> }
<ide>
<ide> return super.getTreeCellRendererComponent(tree, newValue, sel, expanded, leaf, row, hasFocus); |
|
JavaScript | apache-2.0 | e7db89d0bc9572ac69441ace0a42fe4d11274264 | 0 | olirogers/openui5,SAP/openui5,cschuff/openui5,nzamani/openui5,SQCLabs/openui5,SAP/openui5,olirogers/openui5,nzamani/openui5,cschuff/openui5,SAP/openui5,SAP/openui5,SQCLabs/openui5,nzamani/openui5,olirogers/openui5,SQCLabs/openui5,cschuff/openui5 | /*!
* ${copyright}
*/
// Provides control sap.m.Dialog.
sap.ui.define(['jquery.sap.global', './Bar', './InstanceManager', './AssociativeOverflowToolbar', './ToolbarSpacer', './library', 'sap/ui/core/Control', 'sap/ui/core/IconPool', 'sap/ui/core/Popup', 'sap/ui/core/delegate/ScrollEnablement', 'sap/ui/core/theming/Parameters'],
function (jQuery, Bar, InstanceManager, AssociativeOverflowToolbar, ToolbarSpacer, library, Control, IconPool, Popup, ScrollEnablement, Parameters) {
"use strict";
var ValueState = sap.ui.core.ValueState;
var isTheCurrentBrowserIENine = sap.ui.Device.browser.internet_explorer && (sap.ui.Device.browser.version < 10);
/**
* Constructor for a new Dialog.
*
* @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
* The Dialog control is used to interrupt the current processing of an application to prompt the user for information or a response.
* @extends sap.ui.core.Control
* @implements sap.ui.core.PopupInterface
*
* @author SAP SE
* @version ${version}
*
* @constructor
* @public
* @alias sap.m.Dialog
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var Dialog = Control.extend("sap.m.Dialog", /** @lends sap.m.Dialog.prototype */ {
metadata: {
interfaces: [
"sap.ui.core.PopupInterface"
],
library: "sap.m",
properties: {
/**
* Icon displayed in the dialog's header. This icon is invisible on the iOS platform and it's density aware. You can use the density convention (@2, @1.5, etc.) to provide higher resolution image for higher density screen.
*/
icon: {type: "sap.ui.core.URI", group: "Appearance", defaultValue: null},
/**
* Title text appears in the dialog header.
*/
title: {type: "string", group: "Appearance", defaultValue: null},
/**
* Determines whether the header is shown inside the dialog. If this property is set to true, the text and icon property are ignored. This property has a default value true.
* @since 1.15.1
*/
showHeader: {type: "boolean", group: "Appearance", defaultValue: true},
/**
* The type of the dialog. In theme sap_bluecrystal, the type "message" will limit the dialog's width within 480px on tablet and desktop.
*/
type: {type: "sap.m.DialogType", group: "Appearance", defaultValue: sap.m.DialogType.Standard},
/**
* The state affects the icon and the title color. If other than "None" is set, a predefined icon will be added to the dialog. Setting icon property will overwrite the predefined icon. The default value is "None" which doesn't add any icon to the Dialog control. This property is by now only supported by blue crystal theme.
* @since 1.11.2
*/
state: {type: "sap.ui.core.ValueState", group: "Appearance", defaultValue: ValueState.None},
/**
* Determines whether the dialog will displayed on full screen on a phone.
* @since 1.11.2
* @deprecated Since version 1.13.1.
* Please use the new stretch property instead. This enables a stretched dialog even on tablet and desktop. If you want to achieve the same effect as stretchOnPhone, please set the stretch with jQuery.device.is.phone, then dialog is only stretched when runs on phone.
*/
stretchOnPhone: {type: "boolean", group: "Appearance", defaultValue: false, deprecated: true},
/**
* Determines if the dialog will be stretched to full screen. This property is only applicable to standard dialog and message type dialog ignores this property.
* @since 1.13.1
*/
stretch: {type: "boolean", group: "Appearance", defaultValue: false},
/**
* Preferred width of content in Dialog. This property affects the width of dialog on phone in landscape mode, tablet or desktop, because the dialog has a fixed width on phone in portrait mode. If the preferred width is less than the minimum width of dilaog or more than the available width of the screen, it will be overwritten by the min or max value. The current mininum value of dialog width on tablet is 400px.
* @since 1.12.1
*/
contentWidth: {type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: null},
/**
* Preferred height of content in Dialog. If the preferred height is bigger than the available space on screen, it will be overwritten by the maximum available height on screen in order to make sure that dialog isn't cut off.
* @since 1.12.1
*/
contentHeight: {type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: null},
/**
* Indicates if user can scroll horizontally inside dialog when the content is bigger than the content area. However, when scrollable control (sap.m.ScrollContainer, sap.m.Page) is in the dialog, this property needs to be set to false to disable the scrolling in dialog in order to make the scrolling in the child control work properly.
* Dialog detects if there's sap.m.NavContainer, sap.m.Page, or sap.m.ScrollContainer as direct child added to dialog. If there is, dialog will turn off scrolling by setting this property to false automatically ignoring the existing value of this property.
* @since 1.15.1
*/
horizontalScrolling: {type: "boolean", group: "Behavior", defaultValue: true},
/**
* Indicates if user can scroll vertically inside dialog when the content is bignger than the content area. However, when scrollable control (sap.m.ScrollContainer, sap.m.Page) is in the dialog, this property needs to be set to false to disable the scrolling in dialog in order to make the scrolling in the child control work properly.
* Dialog detects if there's sap.m.NavContainer, sap.m.Page, or sap.m.ScrollContainer as direct child added to dialog. If there is, dialog will turn off scrolling by setting this property to false automatically ignoring the existing value of this property.
* @since 1.15.1
*/
verticalScrolling: {type: "boolean", group: "Behavior", defaultValue: true},
/**
* Indicates whether the dialog is resizable. the dialog is resizable. If this property is set to true, the dialog will have a resize handler in it's bottom right corner. This property has a default value false. The Dialog can be resizable only in desktop mode.
* @since 1.30
*/
resizable: {type: "boolean", group: "Behavior", defaultValue: false},
/**
* Indicates whether the dialog is draggable. If this property is set to true, the dialog will be draggable by it's header. This property has a default value false. The Dialog can be draggable only in desktop mode.
* @since 1.30
*/
draggable: {type: "boolean", group: "Behavior", defaultValue: false}
},
defaultAggregation: "content",
aggregations: {
/**
* The content inside the dialog.
*/
content: {type: "sap.ui.core.Control", multiple: true, singularName: "content"},
/**
* When subHeader is assigned to Dialog, it's rendered directly after the main header in Dialog. SubHeader is out of the content area and won't be scrolled when content's size is bigger than the content area's size.
* @since 1.12.2
*/
subHeader: {type: "sap.m.IBar", multiple: false},
/**
* CustomHeader is only supported in theme sap_bluecrystal. When it's set, the icon, title and showHeader are properties ignored. Only the customHeader is shown as the header of the dialog.
* @since 1.15.1
*/
customHeader: {type: "sap.m.IBar", multiple: false},
/**
* The button which is rendered to the left side (right side in RTL mode) of the endButton in the footer area inside the dialog. From UI5 version 1.21.1, there's a new aggregation "buttons" created with which more than 2 buttons can be added to the footer area of dialog. If the new "buttons" aggregation is set, any change made to this aggregation has no effect anymore. When runs on the phone, this button (and the endButton together when set) is (are) rendered at the center of the footer area. When runs on the other platforms, this button (and the endButton together when set) is (are) rendered at the right side (left side in RTL mode) of the footer area.
* @since 1.15.1
*/
beginButton: {type: "sap.m.Button", multiple: false},
/**
* The button which is rendered to the right side (left side in RTL mode) of the beginButton in the footer area inside the dialog. From UI5 version 1.21.1, there's a new aggregation "buttons" created with which more than 2 buttons can be added to the footer area of dialog. If the new "buttons" aggregation is set, any change made to this aggregation has no effect anymore. When runs on the phone, this button (and the beginButton together when set) is (are) rendered at the center of the footer area. When runs on the other platforms, this button (and the beginButton together when set) is (are) rendered at the right side (left side in RTL mode) of the footer area.
* @since 1.15.1
*/
endButton: {type: "sap.m.Button", multiple: false},
/**
* Buttons can be added to the footer area of dialog through this aggregation. When this aggregation is set, any change to beginButton and endButton has no effect anymore. Buttons which are inside this aggregation are aligned at the right side (left side in RTL mode) of the footer instead of in the middle of the footer.
* @since 1.21.1
*/
buttons: {type: "sap.m.Button", multiple: true, singularName: "button"},
/**
* The hidden aggregation for internal maintained header.
*/
_header: {type: "sap.ui.core.Control", multiple: false, visibility: "hidden"},
/**
* The hidden aggregation for internal maintained title control.
*/
_title: {type: "sap.ui.core.Control", multiple: false, visibility: "hidden"},
/**
* The hidden aggregation for internal maintained icon control.
*/
_icon: {type: "sap.ui.core.Control", multiple: false, visibility: "hidden"},
/**
* The hidden aggregation for internal maintained toolbar instance
*/
_toolbar: {type: "sap.m.OverflowToolbar", multiple: false, visibility: "hidden"}
},
associations: {
/**
* LeftButton is shown at the left edge of the bar in iOS, and at the right side of the bar for the other platforms. Please set this to null if you want to remove the left button from the bar. And the button is only removed from the bar, not destroyed. When showHeader is set to false, this property will be ignored. Setting leftButton will also set the beginButton internally.
* @deprecated Since version 1.15.1.
*
* LeftButton has been deprecated since 1.15.1. Please use the beginButton instead which is more RTL friendly.
*/
leftButton: {type: "sap.m.Button", multiple: false, deprecated: true},
/**
* RightButton is always shown at the right edge of the bar. Please set this to null if you want to remove the right button from the bar. And the button is only removed from the bar, not destroyed. When showHeader is set to false, this property will be ignored. Setting rightButton will also set the endButton internally.
* @deprecated Since version 1.15.1.
*
* RightButton has been deprecated since 1.15.1. Please use the endButton instead which is more RTL friendly.
*/
rightButton: {type: "sap.m.Button", multiple: false, deprecated: true},
/**
* Focus is set to the dialog in the sequence of leftButton and rightButton when available. But if some other control needs to get the focus other than one of those two buttons, set the initialFocus with the control which should be focused on. Setting initialFocus to input controls doesn't open the on screen keyboard on mobile device, this is due to the browser limitation that the on screen keyboard can't be opened with javascript code. The opening of on screen keyboard must be triggered by real user action.
* @since 1.15.0
*/
initialFocus: {type: "sap.ui.core.Control", multiple: false},
/**
* Association to controls / ids which describe this control (see WAI-ARIA attribute aria-describedby).
*/
ariaDescribedBy: {type: "sap.ui.core.Control", multiple: true, singularName: "ariaDescribedBy"}
},
events: {
/**
* This event will be fired before the dialog is opened.
*/
beforeOpen: {},
/**
* This event will be fired after the dialog is opened.
*/
afterOpen: {},
/**
* This event will be fired before the dialog is closed.
*/
beforeClose: {
parameters: {
/**
* This indicates the trigger of closing the dialog. If dialog is closed by either leftButton or rightButton, the button that closes the dialog is set to this parameter. Otherwise this parameter is set to null.
* @since 1.9.2
*/
origin: {type: "sap.m.Button"}
}
},
/**
* This event will be fired after the dialog is closed.
*/
afterClose: {
parameters: {
/**
* This indicates the trigger of closing the dialog. If dialog is closed by either leftButton or rightButton, the button that closes the dialog is set to this parameter. Otherwise this parameter is set to null.
* @since 1.9.2
*/
origin: {type: "sap.m.Button"}
}
}
}
}
});
Dialog._bPaddingByDefault = (sap.ui.getCore().getConfiguration().getCompatibilityVersion("sapMDialogWithPadding").compareTo("1.16") < 0);
Dialog._mStateClasses = {};
Dialog._mStateClasses[ValueState.None] = "";
Dialog._mStateClasses[ValueState.Success] = "sapMDialogSuccess";
Dialog._mStateClasses[ValueState.Warning] = "sapMDialogWarning";
Dialog._mStateClasses[ValueState.Error] = "sapMDialogError";
Dialog._mIcons = {};
Dialog._mIcons[ValueState.Success] = IconPool.getIconURI("message-success");
Dialog._mIcons[ValueState.Warning] = IconPool.getIconURI("message-warning");
Dialog._mIcons[ValueState.Error] = IconPool.getIconURI("message-error");
/* =========================================================== */
/* begin: Lifecycle functions */
/* =========================================================== */
Dialog.prototype.init = function () {
var that = this;
this._externalIcon = undefined;
this._oManuallySetSize = null;
this._oManuallySetPosition = null;
// used to judge if enableScrolling needs to be disabled
this._scrollContentList = ["NavContainer", "Page", "ScrollContainer"];
this.oPopup = new Popup();
this.oPopup.setShadow(true);
if (jQuery.device.is.iphone && !this._bMessageType) {
this.oPopup.setModal(true, "sapMDialogTransparentBlk");
} else {
this.oPopup.setModal(true, "sapMDialogBlockLayerInit");
}
this.oPopup.setAnimations(jQuery.proxy(this._openAnimation, this), jQuery.proxy(this._closeAnimation, this));
//keyboard support for desktop environments
//use pseudo event 'onsapescape' to implement keyboard-trigger for closing this dialog
//had to implement this on the popup instance because it did not work on the dialog prototype
this.oPopup.onsapescape = jQuery.proxy(function (oEvent) {
// when the escape is already handled by inner control, nothing should happen inside dialog
if (oEvent.originalEvent && oEvent.originalEvent._sapui_handledByControl) {
return;
}
this.close();
//event should not trigger any further actions
oEvent.stopPropagation();
}, this);
/**
*
* @param {Object} oPosition A new position to move the Dialog to.
* @param {boolean} bFromResize Is the function called from resize event.
* @private
*/
this.oPopup._applyPosition = function (oPosition, bFromResize) {
that._setDimensions();
that._adjustScrollingPane();
//set to hard 50% or the values set from a drag or resize
oPosition.at = {
left: that._oManuallySetPosition ? that._oManuallySetPosition.x : '50%',
top: that._oManuallySetPosition ? that._oManuallySetPosition.y : '50%'
};
Popup.prototype._applyPosition.call(this, oPosition);
};
if (Dialog._bPaddingByDefault) {
this.addStyleClass("sapUiPopupWithPadding");
}
};
Dialog.prototype.onBeforeRendering = function () {
//if content has scrolling, disable scrolling automatically
if (this._hasSingleScrollableContent()) {
this._forceDisableScrolling = true;
jQuery.sap.log.info("VerticalScrolling and horizontalScrolling in sap.m.Dialog with ID " + this.getId() + " has been disabled because there's scrollable content inside");
} else {
this._forceDisableScrolling = false;
}
if (!this._forceDisableScrolling) {
if (!this._oScroller) {
this._oScroller = new ScrollEnablement(this, this.getId() + "-scroll", {
horizontal: this.getHorizontalScrolling(), // will be disabled in adjustScrollingPane if content can fit in
vertical: this.getVerticalScrolling(),
zynga: false,
preventDefault: false,
nonTouchScrolling: "scrollbar",
// In android stock browser, iScroll has to be used
// The scrolling layer using native scrolling is transparent for the browser to dispatch events
iscroll: sap.ui.Device.browser.name === "an" ? "force" : undefined
});
}
}
this._createToolbarButtons();
};
Dialog.prototype.onAfterRendering = function () {
this._$scrollPane = this.$("scroll");
//this is not used in the control itself but is used in test and may me used from client's implementations
this._$content = this.$("cont");
this._$dialog = this.$();
if (this.isOpen()) {
//restore the focus after rendering when dialog is already open
this._setInitialFocus();
}
};
Dialog.prototype.exit = function () {
InstanceManager.removeDialogInstance(this);
if (this.oPopup) {
this.oPopup.detachOpened(this._handleOpened, this);
this.oPopup.detachClosed(this._handleClosed, this);
this.oPopup.destroy();
this.oPopup = null;
}
if (this._oScroller) {
this._oScroller.destroy();
this._oScroller = null;
}
if (this._header) {
this._header.destroy();
this._header = null;
}
if (this._headerTitle) {
this._headerTitle.destroy();
this._headerTitle = null;
}
if (this._iconImage) {
this._iconImage.destroy();
this._iconImage = null;
}
};
/* =========================================================== */
/* end: Lifecycle functions */
/* =========================================================== */
/* =========================================================== */
/* begin: public functions */
/* =========================================================== */
/**
* Open the dialog.
*
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
Dialog.prototype.open = function () {
var oPopup = this.oPopup;
// Set the initial focus to the dialog itself.
// The initial focus should be set because otherwise the first focusable element will be focused.
// This first element can be input or textarea which will trigger the keyboard to open.
// The focus will be change after the dialog is opened;
oPopup.setInitialFocusId(this.getId());
if (oPopup.isOpen()) {
return this;
}
//reset the close trigger
this._oCloseTrigger = null;
this.fireBeforeOpen();
oPopup.attachOpened(this._handleOpened, this);
// Open popup
oPopup.setContent(this);
oPopup.open();
InstanceManager.addDialogInstance(this);
return this;
};
/**
* Close the dialog.
*
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
Dialog.prototype.close = function () {
this.$().removeClass('sapDialogDisableTransition');
//clear the resize listener
jQuery(window).off('resize.sapMDialogWindowResize');
var oPopup = this.oPopup;
var eOpenState = this.oPopup.getOpenState();
if (!(eOpenState === sap.ui.core.OpenState.CLOSED || eOpenState === sap.ui.core.OpenState.CLOSING)) {
sap.m.closeKeyboard();
this.fireBeforeClose({origin: this._oCloseTrigger});
oPopup.attachClosed(this._handleClosed, this);
this._bDisableRepositioning = false;
//reset the drag and/or resize
this._oManuallySetPosition = null;
this._oManuallySetSize = null;
oPopup.close();
}
return this;
};
/**
* The method checks if the Dialog is open. It returns true when the Dialog is currently open (this includes opening and closing animations), otherwise it returns false.
*
* @returns boolean
* @public
* @since 1.9.1
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
Dialog.prototype.isOpen = function () {
return this.oPopup && this.oPopup.isOpen();
};
/* =========================================================== */
/* end: public functions */
/* =========================================================== */
/* =========================================================== */
/* begin: event handlers */
/* =========================================================== */
/**
*
* @private
*/
Dialog.prototype._handleOpened = function () {
this.oPopup.detachOpened(this._handleOpened, this);
this._setInitialFocus();
this.fireAfterOpen();
};
/**
*
* @private
*/
Dialog.prototype._handleClosed = function () {
// TODO: remove the following three lines after the popup open state problem is fixed
if (!this.oPopup) {
return;
}
this.oPopup.detachClosed(this._handleClosed, this);
// Not removing the content DOM leads to the problem that control DOM with the same ID exists in two places if
// the control is added to a different aggregation without the dialog being destroyed. In this special case the
// RichTextEditor (as an example) renders a textarea-element and afterwards tells the TinyMCE component which ID
// to use for rendering; since there are two elements with the same ID at that point, it does not work.
// As the Dialog can only contain other controls, we can safely discard the DOM - we cannot do this inside
// the Popup, since it supports displaying arbitrary HTML content.
this.$().remove();
InstanceManager.removeDialogInstance(this);
this.fireAfterClose({origin: this._oCloseTrigger});
};
/**
* Event handler for the focusin event.
* If it occurs on the focus handler elements at the beginning of the dialog, the focus is set to the end, and vice versa.
* @param {jQuery.EventObject} oEvent The event object
* @private
*/
Dialog.prototype.onfocusin = function (oEvent) {
var oSourceDomRef = oEvent.target;
//Check if the invisible FIRST focusable element (suffix '-firstfe') has gained focus
if (oSourceDomRef.id === this.getId() + "-firstfe") {
//Check if buttons are available
var oLastFocusableDomRef = this.$("footer").lastFocusableDomRef() || this.$("cont").lastFocusableDomRef() || (this.getSubHeader() && this.getSubHeader().$().firstFocusableDomRef()) || (this._getAnyHeader() && this._getAnyHeader().$().lastFocusableDomRef());
if (oLastFocusableDomRef) {
jQuery.sap.focus(oLastFocusableDomRef);
}
} else if (oSourceDomRef.id === this.getId() + "-lastfe") {
//Check if the invisible LAST focusable element (suffix '-lastfe') has gained focus
//First check if header content is available
var oFirstFocusableDomRef = (this._getAnyHeader() && this._getAnyHeader().$().firstFocusableDomRef()) || (this.getSubHeader() && this.getSubHeader().$().firstFocusableDomRef()) || this.$("cont").firstFocusableDomRef() || this.$("footer").firstFocusableDomRef();
if (oFirstFocusableDomRef) {
jQuery.sap.focus(oFirstFocusableDomRef);
}
}
};
/* =========================================================== */
/* end: event handlers */
/* =========================================================== */
/* =========================================================== */
/* begin: private functions */
/* =========================================================== */
/**
*
* @param {Object} $Ref
* @param {number} iRealDuration
* @param fnOpened
* @private
*/
Dialog.prototype._openAnimation = function ($Ref, iRealDuration, fnOpened) {
$Ref.addClass("sapMDialogOpen");
if (isTheCurrentBrowserIENine) {
$Ref.fadeIn(200, fnOpened);
} else {
$Ref.css("display", "block");
setTimeout(fnOpened, 210); // the time should be longer the longest transition in the CSS, because of focusing and transition relate issues
}
};
/**
*
* @param {Object} $Ref
* @param {number} iRealDuration
* @param fnClose
* @private
*/
Dialog.prototype._closeAnimation = function ($Ref, iRealDuration, fnClose) {
$Ref.removeClass("sapMDialogOpen");
if (isTheCurrentBrowserIENine) {
$Ref.fadeOut(200, fnClose);
} else {
setTimeout(fnClose, 210);
}
};
/**
*
* @private
*/
Dialog.prototype._setDimensions = function () {
var $this = this.$(),
bStretch = this.getStretch(),
bStretchOnPhone = this.getStretchOnPhone() && sap.ui.Device.system.phone,
bMessageType = this._bMessageType,
oStyles = {};
//the initial size is set in the renderer when the dom is created
if (!bStretch) {
//set the size to the content
if (!this._oManuallySetSize) {
oStyles.width = this.getContentWidth() || undefined;
oStyles.height = this.getContentHeight() || undefined;
} else {
oStyles.width = this._oManuallySetSize.width;
oStyles.height = this._oManuallySetSize.height;
}
}
if ((bStretch && !bMessageType) || (bStretchOnPhone)) {
this.$().addClass('sapMDialogStretched');
}
$this.css(oStyles);
//In Chrome when the dialog is stretched the footer is not rendered in the right position;
if (window.navigator.userAgent.toLowerCase().indexOf("chrome") !== -1 && this.getStretch()) {
//forcing repaint
$this.find('> footer').css({bottom: '0.001px'});
}
};
/**
*
* @private
*/
Dialog.prototype._adjustScrollingPane = function () {
if (this._oScroller) {
this._oScroller.refresh();
}
};
/**
*
* @private
*/
Dialog.prototype._reposition = function () {
};
/**
*
* @private
*/
Dialog.prototype._repositionAfterOpen = function () {
};
/**\
*
* @private
*/
Dialog.prototype._reapplyPosition = function () {
this._adjustScrollingPane();
};
/**
*
*
* @private
*/
Dialog.prototype._onResize = function () {
};
/**
*
* @private
*/
Dialog.prototype._createHeader = function () {
if (!this._header) {
// set parent of header to detect changes on title
this._header = new Bar(this.getId() + "-header").addStyleClass("sapMDialogTitle");
this.setAggregation("_header", this._header, false);
}
};
/**
* If a scrollable control (sap.m.NavContainer, sap.m.ScrollContainer, sap.m.Page) is added to dialog's content aggregation as a single child or through one or more sap.ui.mvc.View instances,
* the scrolling inside dialog will be disabled in order to avoid wrapped scrolling areas.
*
* If more than one scrollable control is added to dialog, the scrolling needs to be disabled manually.
* @private
*/
Dialog.prototype._hasSingleScrollableContent = function () {
var aContent = this.getContent(), i;
while (aContent.length === 1 && aContent[0] instanceof sap.ui.core.mvc.View) {
aContent = aContent[0].getContent();
}
if (aContent.length === 1) {
for (i = 0; i < this._scrollContentList.length; i++) {
if (aContent[0] instanceof sap.m[this._scrollContentList[i]]) {
return true;
}
}
}
return false;
};
/**
*
* @private
*/
Dialog.prototype._initBlockLayerAnimation = function () {
this.oPopup._hideBlockLayer = function () {
var $blockLayer = jQuery("#sap-ui-blocklayer-popup");
$blockLayer.removeClass("sapMDialogTransparentBlk");
Popup.prototype._hideBlockLayer.call(this);
};
};
/**
*
* @private
*/
Dialog.prototype._clearBlockLayerAnimation = function () {
if (jQuery.device.is.iphone && !this._bMessageType) {
delete this.oPopup._showBlockLayer;
this.oPopup._hideBlockLayer = function () {
var $blockLayer = jQuery("#sap-ui-blocklayer-popup");
$blockLayer.removeClass("sapMDialogTransparentBlk");
Popup.prototype._hideBlockLayer.call(this);
};
}
};
/**
*
* @private
*/
Dialog.prototype._getFocusId = function () {
// Left or Right button can be visible false and therefore not rendered.
// In such a case, focus should be set somewhere else.
return this.getInitialFocus()
|| this._getFirstFocusableContentSubHeader()
|| this._getFirstFocusableContentElementId()
|| this._getFirstVisibleButtonId()
|| this.getId();
};
/**
*
* @returns {string}
* @private
*/
Dialog.prototype._getFirstVisibleButtonId = function () {
var oBeginButton = this.getBeginButton(),
oEndButton = this.getEndButton(),
aButtons = this.getButtons(),
sButtonId = "";
if (oBeginButton && oBeginButton.getVisible()) {
sButtonId = oBeginButton.getId();
} else if (oEndButton && oEndButton.getVisible()) {
sButtonId = oEndButton.getId();
} else if (aButtons && aButtons.length > 0) {
for (var i = 0; i < aButtons.length; i++) {
if (aButtons[i].getVisible()) {
sButtonId = aButtons[i].getId();
break;
}
}
}
return sButtonId;
};
/**
*
* @returns {string}
* @private
*/
Dialog.prototype._getFirstFocusableContentSubHeader = function () {
var $subHeader = this.$().find('.sapMDialogSubHeader');
var sResult;
var oFirstFocusableDomRef = $subHeader.firstFocusableDomRef();
if (oFirstFocusableDomRef) {
sResult = oFirstFocusableDomRef.id;
}
return sResult;
};
/**
*
* @returns {string}
* @private
*/
Dialog.prototype._getFirstFocusableContentElementId = function () {
var sResult = "";
var $dialogContent = this.$("cont");
var oFirstFocusableDomRef = $dialogContent.firstFocusableDomRef();
if (oFirstFocusableDomRef) {
sResult = oFirstFocusableDomRef.id;
}
return sResult;
};
// The control that needs to be focused after dialog is open is calculated in following sequence:
// initialFocus, first focusable element in content area, beginButton, endButton
// dialog is always modal so the focus doen't need to be on the dialog when there's
// no initialFocus, beginButton and endButton available, but to keep the consistency,
// the focus will in the end fall back to dialog itself.
/**
*
* @private
*/
Dialog.prototype._setInitialFocus = function () {
var sFocusId = this._getFocusId();
var oControl = sap.ui.getCore().byId(sFocusId);
var oFocusDomRef;
if (oControl) {
//if someone tryies to focus an existing but not visible control, focus the Dialog itself.
if (!oControl.getVisible()) {
this.focus();
return;
}
oFocusDomRef = oControl.getFocusDomRef();
}
oFocusDomRef = oFocusDomRef || jQuery.sap.domById(sFocusId);
//if there is no set initial focus, set the default one to the initialFocus association
if (!this.getInitialFocus()) {
this.setAssociation('initialFocus', oFocusDomRef ? oFocusDomRef.id : this.getId(), true);
}
// Setting focus to DOM Element which can open the on screen keyboard on mobile device doesn't work
// consistently across devices. Therefore setting focus to those elements are disabled on mobile devices
// and the keyboard should be opened by the User explicitly
if (sap.ui.Device.system.desktop || (oFocusDomRef && !/input|textarea|select/i.test(oFocusDomRef.tagName))) {
jQuery.sap.focus(oFocusDomRef);
} else {
// Set the focus to the popup itself in order to keep the tab chain
this.focus();
}
};
/**
* Returns the sap.ui.core.ScrollEnablement delegate which is used with this control.
*
* @private
*/
Dialog.prototype.getScrollDelegate = function () {
return this._oScroller;
};
/**
*
* @param {string} sPos
* @returns {string}
* @private
*/
Dialog.prototype._composeAggreNameInHeader = function (sPos) {
var sHeaderAggregationName;
if (sPos === "Begin") {
sHeaderAggregationName = "contentLeft";
} else if (sPos === "End") {
sHeaderAggregationName = "contentRight";
} else {
sHeaderAggregationName = "content" + sPos;
}
return sHeaderAggregationName;
};
/**
*
* @returns {boolean}
* @private
*/
Dialog.prototype._isToolbarEmpty = function () {
// no ToolbarSpacer
var filteredContent = this._oToolbar.getContent().filter(function (content) {
return content.getMetadata().getName() !== 'sap.m.ToolbarSpacer';
});
return filteredContent.length === 0;
};
/**
*
* @param {Object} oButton
* @param {string} sPos
* @param {boolean} bSkipFlag
* @returns {Dialog}
* @private
*/
Dialog.prototype._setButton = function (oButton, sPos, bSkipFlag) {
return this;
};
/**
*
* @param {string} sPos
* @private
*/
Dialog.prototype._getButton = function (sPos) {
var sAggregationName = sPos.toLowerCase() + "Button",
sButtonName = "_o" + this._firstLetterUpperCase(sPos) + "Button";
if (sap.ui.Device.system.phone) {
return this.getAggregation(sAggregationName, null, /*avoid infinite loop*/true);
} else {
return this[sButtonName];
}
};
/**
*
* @param {string} sPos
* @private
*/
Dialog.prototype._getButtonFromHeader = function (sPos) {
if (this._header) {
var sHeaderAggregationName = this._composeAggreNameInHeader(this._firstLetterUpperCase(sPos)),
aContent = this._header.getAggregation(sHeaderAggregationName);
return aContent && aContent[0];
} else {
return null;
}
};
/**
*
* @param {string} sValue
* @returns {string}
* @private
*/
Dialog.prototype._firstLetterUpperCase = function (sValue) {
return sValue.charAt(0).toUpperCase() + sValue.slice(1);
};
/**
* Returns the custom header instance when the customHeader aggregation is set. Otherwise it returns the internal managed
* header instance. This method can be called within composite controls which use sap.m.Dialog inside.
*
* @protected
*/
Dialog.prototype._getAnyHeader = function () {
var oCustomHeader = this.getCustomHeader();
if (oCustomHeader) {
return oCustomHeader;
} else {
var bShowHeader = this.getShowHeader();
// if showHeader is set to false and not for standard dialog in iOS in theme sap_mvi, no header.
if (!bShowHeader) {
return null;
}
this._createHeader();
return this._header;
}
};
/**
*
* @private
*/
Dialog.prototype._deregisterResizeHandler = function () {
};
/**
*
* @private
*/
Dialog.prototype._registerResizeHandler = function () {
};
Dialog.prototype._createToolbarButtons = function () {
var toolbar = this._getToolbar();
var buttons = this.getButtons();
var beginButton = this.getBeginButton();
var endButton = this.getEndButton();
toolbar.removeAllContent();
toolbar.addContent(new ToolbarSpacer());
//if there are buttons they should be in the toolbar and the begin and end buttons should not be used
if (buttons && buttons.length) {
buttons.forEach(function (button) {
toolbar.addContent(button);
});
} else {
if (beginButton) {
toolbar.addContent(beginButton);
}
if (endButton) {
toolbar.addContent(endButton);
}
}
};
/*
*
* @returns {*|sap.m.IBar|null}
* @private
*/
Dialog.prototype._getToolbar = function () {
if (!this._oToolbar) {
this._oToolbar = new AssociativeOverflowToolbar(this.getId() + "-footer").addStyleClass("sapMTBNoBorders").applyTagAndContextClassFor("footer");
this._oToolbar._isControlsInfoCached = function () {
return false;
};
this.setAggregation("_toolbar", this._oToolbar);
}
return this._oToolbar;
};
/* =========================================================== */
/* end: private functions */
/* =========================================================== */
/* =========================================================== */
/* begin: setters */
/* =========================================================== */
//Manage "sapMDialogWithSubHeader" class depending on the visibility of the subHeader
//This is because the dialog has content height and width and the box-sizing have to be content-box in
//order to not recalculate the size with js
Dialog.prototype.setSubHeader = function (oControl) {
this.setAggregation("subHeader", oControl);
if (oControl) {
oControl.setVisible = function (isVisible) {
this.$().toggleClass('sapMDialogWithSubHeader', isVisible);
oControl.setProperty("visible", isVisible);
}.bind(this);
}
return oControl;
};
//The public setters and getters should not be documented via JSDoc because they will appear in the explored app
Dialog.prototype.setLeftButton = function (vButton) {
if (!(vButton instanceof sap.m.Button)) {
vButton = sap.ui.getCore().byId(vButton);
}
//setting leftButton will also set the beginButton with the same button instance.
//as this instance is aggregated by the beginButton, the hidden aggregation isn't needed.
this.setBeginButton(vButton);
return this.setAssociation("leftButton", vButton);
};
Dialog.prototype.setRightButton = function (vButton) {
if (!(vButton instanceof sap.m.Button)) {
vButton = sap.ui.getCore().byId(vButton);
}
//setting rightButton will also set the endButton with the same button instance.
//as this instance is aggregated by the endButton, the hidden aggregation isn't needed.
this.setEndButton(vButton);
return this.setAssociation("rightButton", vButton);
};
Dialog.prototype.getLeftButton = function () {
var oBeginButton = this.getBeginButton();
return oBeginButton ? oBeginButton.getId() : null;
};
Dialog.prototype.getRightButton = function () {
var oEndButton = this.getEndButton();
return oEndButton ? oEndButton.getId() : null;
};
//get buttons should return the buttons, beginButton and endButton aggregations
Dialog.prototype.getAggregation = function (sAggregationName, oDefaultForCreation, bPassBy) {
var originalResponse = Control.prototype.getAggregation.apply(this, Array.prototype.slice.call(arguments, 0, 2));
//if no buttons are set returns the begin and end buttons
if (sAggregationName === 'buttons' && originalResponse.length === 0) {
this.getBeginButton() && originalResponse.push(this.getBeginButton());
this.getEndButton() && originalResponse.push(this.getEndButton());
}
return originalResponse;
};
Dialog.prototype.setTitle = function (sTitle) {
this.setProperty("title", sTitle, true);
if (this._headerTitle) {
this._headerTitle.setText(sTitle);
} else {
this._headerTitle = new sap.m.Title(this.getId() + "-title", {
text: sTitle,
level: "H1"
}).addStyleClass("sapMDialogTitle");
this._createHeader();
this._header.addContentMiddle(this._headerTitle);
}
return this;
};
Dialog.prototype.setCustomHeader = function (oCustomHeader) {
if (oCustomHeader) {
oCustomHeader.addStyleClass("sapMDialogTitle");
}
this.setAggregation("customHeader", oCustomHeader);
};
Dialog.prototype.setState = function (sState) {
var mFlags = {},
$this = this.$(),
sName;
mFlags[sState] = true;
this.setProperty("state", sState, true);
for (sName in Dialog._mStateClasses) {
$this.toggleClass(Dialog._mStateClasses[sName], !!mFlags[sName]);
}
this.setIcon(Dialog._mIcons[sState], true);
};
Dialog.prototype.setIcon = function (sIcon, bInternal) {
if (!bInternal) {
this._externalIcon = sIcon;
} else {
if (this._externalIcon) {
sIcon = this._externalIcon;
}
}
if (sIcon) {
if (sIcon !== this.getIcon()) {
if (this._iconImage) {
this._iconImage.setSrc(sIcon);
} else {
this._iconImage = IconPool.createControlByURI({
id: this.getId() + "-icon",
src: sIcon,
useIconTooltip: false
}, sap.m.Image).addStyleClass("sapMDialogIcon");
this._createHeader();
this._header.insertAggregation("contentMiddle", this._iconImage, 0);
}
}
} else {
var sDialogState = this.getState();
if (!bInternal && sDialogState !== ValueState.None) {
if (this._iconImage) {
this._iconImage.setSrc(Dialog._mIcons[sDialogState]);
}
} else {
if (this._iconImage) {
this._iconImage.destroy();
this._iconImage = null;
}
}
}
this.setProperty("icon", sIcon, true);
return this;
};
Dialog.prototype.setType = function (sType) {
var sOldType = this.getType();
if (sOldType === sType) {
return this;
}
this._bMessageType = (sType === sap.m.DialogType.Message);
return this.setProperty("type", sType, false);
};
Dialog.prototype.setStretch = function (bStretch) {
this._bStretchSet = true;
return this.setProperty("stretch", bStretch);
};
Dialog.prototype.setStretchOnPhone = function (bStretchOnPhone) {
if (this._bStretchSet) {
jQuery.sap.log.warning("sap.m.Dialog: stretchOnPhone property is deprecated. Setting stretchOnPhone property is ignored when there's already stretch property set.");
return this;
}
this.setProperty("stretchOnPhone", bStretchOnPhone);
return this.setProperty("stretch", bStretchOnPhone && sap.ui.Device.system.phone);
};
Dialog.prototype.setVerticalScrolling = function (bValue) {
var oldValue = this.getVerticalScrolling();
if (oldValue === bValue) {
return this;
}
this.$().toggleClass("sapMDialogVerScrollDisabled", !bValue);
this.setProperty("verticalScrolling", bValue);
if (this._oScroller) {
this._oScroller.setVertical(bValue);
}
return this;
};
Dialog.prototype.setHorizontalScrolling = function (bValue) {
var oldValue = this.getHorizontalScrolling();
if (oldValue === bValue) {
return this;
}
this.$().toggleClass("sapMDialogHorScrollDisabled", !bValue);
this.setProperty("horizontalScrolling", bValue);
if (this._oScroller) {
this._oScroller.setHorizontal(bValue);
}
return this;
};
Dialog.prototype.setInitialFocus = function (sInitialFocus) {
// Skip the invalidation when sets the initial focus
//
// The initial focus takes effect after the next open of the dialog, when it's set
// after the dialog is open, the current focus won't be changed
// SelectDialog depends on this. If this has to be changed later, please make sure to
// check the SelectDialog as well where setIntialFocus is called.
return this.setAssociation("initialFocus", sInitialFocus, true);
};
/* =========================================================== */
/* end: setters */
/* =========================================================== */
Dialog.prototype.forceInvalidate = Control.prototype.invalidate;
// stop propagating the invalidate to static UIArea before dialog is opened.
// otherwise the open animation can't be seen
// dialog will be rendered directly to static ui area when the open method is called.
Dialog.prototype.invalidate = function (oOrigin) {
if (this.isOpen()) {
this.forceInvalidate(oOrigin);
}
};
/* =========================================================== */
/* Resize & Drag logic */
/* =========================================================== */
/**
*
* @param {Object} eventTarget
* @returns {boolean}
*/
function isHeaderClicked(eventTarget) {
var $target = jQuery(eventTarget);
var oControl = $target.control(0);
if (!oControl || oControl.getMetadata().getInterfaces().indexOf("sap.m.IBar") > -1) {
return true;
}
return $target.hasClass('sapMDialogTitle');
}
if (sap.ui.Device.system.desktop) {
/**
*
* @param {Object} e
*/
Dialog.prototype.ondblclick = function (e) {
if (isHeaderClicked(e.target)) {
this._bDisableRepositioning = false;
this._oManuallySetPosition = null;
this._oManuallySetSize = null;
//call the reposition
this.oPopup && this.oPopup._applyPosition(this.oPopup._oLastPosition, true);
this._$dialog.removeClass('sapMDialogTouched');
}
};
/**
*
* @param {Object} e
*/
Dialog.prototype.onmousedown = function (e) {
if (e.which === 3) {
return; // on right click don't reposition the dialog
}
if (this.getStretch() || (!this.getDraggable() && !this.getResizable())) {
return;
}
var timeout;
var that = this;
var $w = jQuery(document);
var $target = jQuery(e.target);
var bResize = $target.hasClass('sapMDialogResizeHandler') && this.getResizable();
var fnMouseMoveHandler = function (action) {
timeout = timeout ? clearTimeout(timeout) : setTimeout(function () {
action();
}, 0);
};
var initial = {
x: e.pageX,
y: e.pageY,
width: that._$dialog.width(),
height: that._$dialog.height(),
offset: {
//use e.originalEvent.layerX/Y for Firefox
x: e.offsetX ? e.offsetX : e.originalEvent.layerX,
y: e.offsetY ? e.offsetY : e.originalEvent.layerY
},
position: {
x: that._$dialog.offset().left,
y: that._$dialog.offset().top
}
};
if ((isHeaderClicked(e.target) && this.getDraggable()) || bResize) {
that._bDisableRepositioning = true;
that._$dialog.addClass('sapDialogDisableTransition');
//remove the transform translate
that._$dialog.addClass('sapMDialogTouched');
that._oManuallySetPosition = {
x: initial.position.x,
y: initial.position.y
};
//set the new position of the dialog on mouse down when the transform is disabled by the class
that._$dialog.css({
left: that._oManuallySetPosition.x,
top: that._oManuallySetPosition.y
});
}
if (isHeaderClicked(e.target) && this.getDraggable()) {
$w.on("mousemove.sapMDialog", function (e) {
fnMouseMoveHandler(function () {
that._bDisableRepositioning = true;
that._oManuallySetPosition = {
x: e.pageX - initial.offset.x,
y: e.pageY - initial.offset.y
};
//move the dialog
that._$dialog.css({
left: that._oManuallySetPosition.x,
top: that._oManuallySetPosition.y
});
});
});
} else if (bResize) {
that._$dialog.addClass('sapMDialogResizing');
var isInRTLMode = sap.ui.getCore().getConfiguration().getRTL();
var styles = {};
var minWidth = parseInt(that._$dialog.css('min-width'), 10);
var maxLeftOffset = initial.x + initial.width - minWidth;
$w.on("mousemove.sapMDialog", function (e) {
fnMouseMoveHandler(function () {
that._bDisableRepositioning = true;
that._oManuallySetSize = {
width: initial.width + e.pageX - initial.x,
height: initial.height + e.pageY - initial.y
};
if (isInRTLMode) {
styles.left = Math.min(Math.max(e.pageX, 0), maxLeftOffset);
that._oManuallySetSize.width = initial.width + initial.x - Math.max(e.pageX, 0);
}
styles.width = that._oManuallySetSize.width;
styles.height = that._oManuallySetSize.height;
that._$dialog.css(styles);
});
});
} else {
return;
}
$w.on("mouseup.sapMDialog", function () {
$w.off("mouseup.sapMDialog, mousemove.sapMDialog");
if (bResize) {
that._$dialog.removeClass('sapMDialogResizing');
}
});
e.preventDefault();
e.stopPropagation();
};
}
return Dialog;
}, /* bExport= */ true);
| src/sap.m/src/sap/m/Dialog.js | /*!
* ${copyright}
*/
// Provides control sap.m.Dialog.
sap.ui.define(['jquery.sap.global', './Bar', './InstanceManager', './AssociativeOverflowToolbar', './ToolbarSpacer', './library', 'sap/ui/core/Control', 'sap/ui/core/IconPool', 'sap/ui/core/Popup', 'sap/ui/core/delegate/ScrollEnablement', 'sap/ui/core/theming/Parameters'],
function (jQuery, Bar, InstanceManager, AssociativeOverflowToolbar, ToolbarSpacer, library, Control, IconPool, Popup, ScrollEnablement, Parameters) {
"use strict";
var ValueState = sap.ui.core.ValueState;
var isTheCurrentBrowserIENine = sap.ui.Device.browser.internet_explorer && (sap.ui.Device.browser.version < 10);
/**
* Constructor for a new Dialog.
*
* @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
* The Dialog control is used to interrupt the current processing of an application to prompt the user for information or a response.
* @extends sap.ui.core.Control
* @implements sap.ui.core.PopupInterface
*
* @author SAP SE
* @version ${version}
*
* @constructor
* @public
* @alias sap.m.Dialog
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var Dialog = Control.extend("sap.m.Dialog", /** @lends sap.m.Dialog.prototype */ {
metadata: {
interfaces: [
"sap.ui.core.PopupInterface"
],
library: "sap.m",
properties: {
/**
* Icon displayed in the dialog's header. This icon is invisible on the iOS platform and it's density aware. You can use the density convention (@2, @1.5, etc.) to provide higher resolution image for higher density screen.
*/
icon: {type: "sap.ui.core.URI", group: "Appearance", defaultValue: null},
/**
* Title text appears in the dialog header.
*/
title: {type: "string", group: "Appearance", defaultValue: null},
/**
* Determines whether the header is shown inside the dialog. If this property is set to true, the text and icon property are ignored. This property has a default value true.
* @since 1.15.1
*/
showHeader: {type: "boolean", group: "Appearance", defaultValue: true},
/**
* The type of the dialog. In theme sap_bluecrystal, the type "message" will limit the dialog's width within 480px on tablet and desktop.
*/
type: {type: "sap.m.DialogType", group: "Appearance", defaultValue: sap.m.DialogType.Standard},
/**
* The state affects the icon and the title color. If other than "None" is set, a predefined icon will be added to the dialog. Setting icon property will overwrite the predefined icon. The default value is "None" which doesn't add any icon to the Dialog control. This property is by now only supported by blue crystal theme.
* @since 1.11.2
*/
state: {type: "sap.ui.core.ValueState", group: "Appearance", defaultValue: ValueState.None},
/**
* Determines whether the dialog will displayed on full screen on a phone.
* @since 1.11.2
* @deprecated Since version 1.13.1.
* Please use the new stretch property instead. This enables a stretched dialog even on tablet and desktop. If you want to achieve the same effect as stretchOnPhone, please set the stretch with jQuery.device.is.phone, then dialog is only stretched when runs on phone.
*/
stretchOnPhone: {type: "boolean", group: "Appearance", defaultValue: false, deprecated: true},
/**
* Determines if the dialog will be stretched to full screen. This property is only applicable to standard dialog and message type dialog ignores this property.
* @since 1.13.1
*/
stretch: {type: "boolean", group: "Appearance", defaultValue: false},
/**
* Preferred width of content in Dialog. This property affects the width of dialog on phone in landscape mode, tablet or desktop, because the dialog has a fixed width on phone in portrait mode. If the preferred width is less than the minimum width of dilaog or more than the available width of the screen, it will be overwritten by the min or max value. The current mininum value of dialog width on tablet is 400px.
* @since 1.12.1
*/
contentWidth: {type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: null},
/**
* Preferred height of content in Dialog. If the preferred height is bigger than the available space on screen, it will be overwritten by the maximum available height on screen in order to make sure that dialog isn't cut off.
* @since 1.12.1
*/
contentHeight: {type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: null},
/**
* Indicates if user can scroll horizontally inside dialog when the content is bigger than the content area. However, when scrollable control (sap.m.ScrollContainer, sap.m.Page) is in the dialog, this property needs to be set to false to disable the scrolling in dialog in order to make the scrolling in the child control work properly.
* Dialog detects if there's sap.m.NavContainer, sap.m.Page, or sap.m.ScrollContainer as direct child added to dialog. If there is, dialog will turn off scrolling by setting this property to false automatically ignoring the existing value of this property.
* @since 1.15.1
*/
horizontalScrolling: {type: "boolean", group: "Behavior", defaultValue: true},
/**
* Indicates if user can scroll vertically inside dialog when the content is bignger than the content area. However, when scrollable control (sap.m.ScrollContainer, sap.m.Page) is in the dialog, this property needs to be set to false to disable the scrolling in dialog in order to make the scrolling in the child control work properly.
* Dialog detects if there's sap.m.NavContainer, sap.m.Page, or sap.m.ScrollContainer as direct child added to dialog. If there is, dialog will turn off scrolling by setting this property to false automatically ignoring the existing value of this property.
* @since 1.15.1
*/
verticalScrolling: {type: "boolean", group: "Behavior", defaultValue: true},
/**
* Indicates whether the dialog is resizable. the dialog is resizable. If this property is set to true, the dialog will have a resize handler in it's bottom right corner. This property has a default value false. The Dialog can be resizable only in desktop mode.
* @since 1.30
*/
resizable: {type: "boolean", group: "Behavior", defaultValue: false},
/**
* Indicates whether the dialog is draggable. If this property is set to true, the dialog will be draggable by it's header. This property has a default value false. The Dialog can be draggable only in desktop mode.
* @since 1.30
*/
draggable: {type: "boolean", group: "Behavior", defaultValue: false}
},
defaultAggregation: "content",
aggregations: {
/**
* The content inside the dialog.
*/
content: {type: "sap.ui.core.Control", multiple: true, singularName: "content"},
/**
* When subHeader is assigned to Dialog, it's rendered directly after the main header in Dialog. SubHeader is out of the content area and won't be scrolled when content's size is bigger than the content area's size.
* @since 1.12.2
*/
subHeader: {type: "sap.m.IBar", multiple: false},
/**
* CustomHeader is only supported in theme sap_bluecrystal. When it's set, the icon, title and showHeader are properties ignored. Only the customHeader is shown as the header of the dialog.
* @since 1.15.1
*/
customHeader: {type: "sap.m.IBar", multiple: false},
/**
* The button which is rendered to the left side (right side in RTL mode) of the endButton in the footer area inside the dialog. From UI5 version 1.21.1, there's a new aggregation "buttons" created with which more than 2 buttons can be added to the footer area of dialog. If the new "buttons" aggregation is set, any change made to this aggregation has no effect anymore. When runs on the phone, this button (and the endButton together when set) is (are) rendered at the center of the footer area. When runs on the other platforms, this button (and the endButton together when set) is (are) rendered at the right side (left side in RTL mode) of the footer area.
* @since 1.15.1
*/
beginButton: {type: "sap.m.Button", multiple: false},
/**
* The button which is rendered to the right side (left side in RTL mode) of the beginButton in the footer area inside the dialog. From UI5 version 1.21.1, there's a new aggregation "buttons" created with which more than 2 buttons can be added to the footer area of dialog. If the new "buttons" aggregation is set, any change made to this aggregation has no effect anymore. When runs on the phone, this button (and the beginButton together when set) is (are) rendered at the center of the footer area. When runs on the other platforms, this button (and the beginButton together when set) is (are) rendered at the right side (left side in RTL mode) of the footer area.
* @since 1.15.1
*/
endButton: {type: "sap.m.Button", multiple: false},
/**
* Buttons can be added to the footer area of dialog through this aggregation. When this aggregation is set, any change to beginButton and endButton has no effect anymore. Buttons which are inside this aggregation are aligned at the right side (left side in RTL mode) of the footer instead of in the middle of the footer.
* @since 1.21.1
*/
buttons: {type: "sap.m.Button", multiple: true, singularName: "button"},
/**
* The hidden aggregation for internal maintained header.
*/
_header: {type: "sap.ui.core.Control", multiple: false, visibility: "hidden"},
/**
* The hidden aggregation for internal maintained title control.
*/
_title: {type: "sap.ui.core.Control", multiple: false, visibility: "hidden"},
/**
* The hidden aggregation for internal maintained icon control.
*/
_icon: {type: "sap.ui.core.Control", multiple: false, visibility: "hidden"},
/**
* The hidden aggregation for internal maintained toolbar instance
*/
_toolbar: {type: "sap.m.OverflowToolbar", multiple: false, visibility: "hidden"}
},
associations: {
/**
* LeftButton is shown at the left edge of the bar in iOS, and at the right side of the bar for the other platforms. Please set this to null if you want to remove the left button from the bar. And the button is only removed from the bar, not destroyed. When showHeader is set to false, this property will be ignored. Setting leftButton will also set the beginButton internally.
* @deprecated Since version 1.15.1.
*
* LeftButton has been deprecated since 1.15.1. Please use the beginButton instead which is more RTL friendly.
*/
leftButton: {type: "sap.m.Button", multiple: false, deprecated: true},
/**
* RightButton is always shown at the right edge of the bar. Please set this to null if you want to remove the right button from the bar. And the button is only removed from the bar, not destroyed. When showHeader is set to false, this property will be ignored. Setting rightButton will also set the endButton internally.
* @deprecated Since version 1.15.1.
*
* RightButton has been deprecated since 1.15.1. Please use the endButton instead which is more RTL friendly.
*/
rightButton: {type: "sap.m.Button", multiple: false, deprecated: true},
/**
* Focus is set to the dialog in the sequence of leftButton and rightButton when available. But if some other control needs to get the focus other than one of those two buttons, set the initialFocus with the control which should be focused on. Setting initialFocus to input controls doesn't open the on screen keyboard on mobile device, this is due to the browser limitation that the on screen keyboard can't be opened with javascript code. The opening of on screen keyboard must be triggered by real user action.
* @since 1.15.0
*/
initialFocus: {type: "sap.ui.core.Control", multiple: false},
/**
* Association to controls / ids which describe this control (see WAI-ARIA attribute aria-describedby).
*/
ariaDescribedBy: {type: "sap.ui.core.Control", multiple: true, singularName: "ariaDescribedBy"}
},
events: {
/**
* This event will be fired before the dialog is opened.
*/
beforeOpen: {},
/**
* This event will be fired after the dialog is opened.
*/
afterOpen: {},
/**
* This event will be fired before the dialog is closed.
*/
beforeClose: {
parameters: {
/**
* This indicates the trigger of closing the dialog. If dialog is closed by either leftButton or rightButton, the button that closes the dialog is set to this parameter. Otherwise this parameter is set to null.
* @since 1.9.2
*/
origin: {type: "sap.m.Button"}
}
},
/**
* This event will be fired after the dialog is closed.
*/
afterClose: {
parameters: {
/**
* This indicates the trigger of closing the dialog. If dialog is closed by either leftButton or rightButton, the button that closes the dialog is set to this parameter. Otherwise this parameter is set to null.
* @since 1.9.2
*/
origin: {type: "sap.m.Button"}
}
}
}
}
});
Dialog._bPaddingByDefault = (sap.ui.getCore().getConfiguration().getCompatibilityVersion("sapMDialogWithPadding").compareTo("1.16") < 0);
Dialog._mStateClasses = {};
Dialog._mStateClasses[ValueState.None] = "";
Dialog._mStateClasses[ValueState.Success] = "sapMDialogSuccess";
Dialog._mStateClasses[ValueState.Warning] = "sapMDialogWarning";
Dialog._mStateClasses[ValueState.Error] = "sapMDialogError";
Dialog._mIcons = {};
Dialog._mIcons[ValueState.Success] = IconPool.getIconURI("message-success");
Dialog._mIcons[ValueState.Warning] = IconPool.getIconURI("message-warning");
Dialog._mIcons[ValueState.Error] = IconPool.getIconURI("message-error");
/* =========================================================== */
/* begin: Lifecycle functions */
/* =========================================================== */
Dialog.prototype.init = function () {
var that = this;
this._externalIcon = undefined;
this._oManuallySetSize = null;
this._oManuallySetPosition = null;
// used to judge if enableScrolling needs to be disabled
this._scrollContentList = ["NavContainer", "Page", "ScrollContainer"];
this.oPopup = new Popup();
this.oPopup.setShadow(true);
if (jQuery.device.is.iphone && !this._bMessageType) {
this.oPopup.setModal(true, "sapMDialogTransparentBlk");
} else {
this.oPopup.setModal(true, "sapMDialogBlockLayerInit");
}
this.oPopup.setAnimations(jQuery.proxy(this._openAnimation, this), jQuery.proxy(this._closeAnimation, this));
//keyboard support for desktop environments
//use pseudo event 'onsapescape' to implement keyboard-trigger for closing this dialog
//had to implement this on the popup instance because it did not work on the dialog prototype
this.oPopup.onsapescape = jQuery.proxy(function (oEvent) {
// when the escape is already handled by inner control, nothing should happen inside dialog
if (oEvent.originalEvent && oEvent.originalEvent._sapui_handledByControl) {
return;
}
this.close();
//event should not trigger any further actions
oEvent.stopPropagation();
}, this);
/**
*
* @param {Object} oPosition A new position to move the Dialog to.
* @param {boolean} bFromResize Is the function called from resize event.
* @private
*/
this.oPopup._applyPosition = function (oPosition, bFromResize) {
that._setDimensions();
that._adjustScrollingPane();
//set to hard 50% or the values set from a drag or resize
oPosition.at = {
left: that._oManuallySetPosition ? that._oManuallySetPosition.x : '50%',
top: that._oManuallySetPosition ? that._oManuallySetPosition.y : '50%'
};
Popup.prototype._applyPosition.call(this, oPosition);
};
if (Dialog._bPaddingByDefault) {
this.addStyleClass("sapUiPopupWithPadding");
}
};
Dialog.prototype.onBeforeRendering = function () {
//if content has scrolling, disable scrolling automatically
if (this._hasSingleScrollableContent()) {
this._forceDisableScrolling = true;
jQuery.sap.log.info("VerticalScrolling and horizontalScrolling in sap.m.Dialog with ID " + this.getId() + " has been disabled because there's scrollable content inside");
} else {
this._forceDisableScrolling = false;
}
if (!this._forceDisableScrolling) {
if (!this._oScroller) {
this._oScroller = new ScrollEnablement(this, this.getId() + "-scroll", {
horizontal: this.getHorizontalScrolling(), // will be disabled in adjustScrollingPane if content can fit in
vertical: this.getVerticalScrolling(),
zynga: false,
preventDefault: false,
nonTouchScrolling: "scrollbar",
// In android stock browser, iScroll has to be used
// The scrolling layer using native scrolling is transparent for the browser to dispatch events
iscroll: sap.ui.Device.browser.name === "an" ? "force" : undefined
});
}
}
this._createToolbarButtons();
};
Dialog.prototype.onAfterRendering = function () {
this._$scrollPane = this.$("scroll");
//this is not used in the control itself but is used in test and may me used from client's implementations
this._$content = this.$("cont");
this._$dialog = this.$();
if (this.isOpen()) {
//restore the focus after rendering when dialog is already open
this._setInitialFocus();
}
};
Dialog.prototype.exit = function () {
InstanceManager.removeDialogInstance(this);
if (this.oPopup) {
this.oPopup.detachOpened(this._handleOpened, this);
this.oPopup.detachClosed(this._handleClosed, this);
this.oPopup.destroy();
this.oPopup = null;
}
if (this._oScroller) {
this._oScroller.destroy();
this._oScroller = null;
}
if (this._header) {
this._header.destroy();
this._header = null;
}
if (this._headerTitle) {
this._headerTitle.destroy();
this._headerTitle = null;
}
if (this._iconImage) {
this._iconImage.destroy();
this._iconImage = null;
}
};
/* =========================================================== */
/* end: Lifecycle functions */
/* =========================================================== */
/* =========================================================== */
/* begin: public functions */
/* =========================================================== */
/**
* Open the dialog.
*
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
Dialog.prototype.open = function () {
var oPopup = this.oPopup;
// Set the initial focus to the dialog itself.
// The initial focus should be set because otherwise the first focusable element will be focused.
// This first element can be input or textarea which will trigger the keyboard to open.
// The focus will be change after the dialog is opened;
oPopup.setInitialFocusId(this.getId());
if (oPopup.isOpen()) {
return this;
}
//reset the close trigger
this._oCloseTrigger = null;
this.fireBeforeOpen();
oPopup.attachOpened(this._handleOpened, this);
// Open popup
oPopup.setContent(this);
oPopup.open();
//resize handler ===========================================================================================
var __delayTimer;
jQuery(window).on('resize.sapMDialogWindowResize', function () {
if (__delayTimer) {
__delayTimer = clearTimeout(__delayTimer);
}
__delayTimer = setTimeout(this._onResize.bind(this), 50);
}.bind(this));
//set the content size so the scroller can work properly
this._onResize();
InstanceManager.addDialogInstance(this);
return this;
};
/**
* Close the dialog.
*
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
Dialog.prototype.close = function () {
this.$().removeClass('sapDialogDisableTransition');
//clear the resize listener
jQuery(window).off('resize.sapMDialogWindowResize');
var oPopup = this.oPopup;
var eOpenState = this.oPopup.getOpenState();
if (!(eOpenState === sap.ui.core.OpenState.CLOSED || eOpenState === sap.ui.core.OpenState.CLOSING)) {
sap.m.closeKeyboard();
this.fireBeforeClose({origin: this._oCloseTrigger});
oPopup.attachClosed(this._handleClosed, this);
this._bDisableRepositioning = false;
//reset the drag and/or resize
this._oManuallySetPosition = null;
this._oManuallySetSize = null;
oPopup.close();
}
return this;
};
/**
* The method checks if the Dialog is open. It returns true when the Dialog is currently open (this includes opening and closing animations), otherwise it returns false.
*
* @returns boolean
* @public
* @since 1.9.1
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
Dialog.prototype.isOpen = function () {
return this.oPopup && this.oPopup.isOpen();
};
/* =========================================================== */
/* end: public functions */
/* =========================================================== */
/* =========================================================== */
/* begin: event handlers */
/* =========================================================== */
/**
*
* @private
*/
Dialog.prototype._handleOpened = function () {
this.oPopup.detachOpened(this._handleOpened, this);
this._setInitialFocus();
this.fireAfterOpen();
};
/**
*
* @private
*/
Dialog.prototype._handleClosed = function () {
// TODO: remove the following three lines after the popup open state problem is fixed
if (!this.oPopup) {
return;
}
this.oPopup.detachClosed(this._handleClosed, this);
// Not removing the content DOM leads to the problem that control DOM with the same ID exists in two places if
// the control is added to a different aggregation without the dialog being destroyed. In this special case the
// RichTextEditor (as an example) renders a textarea-element and afterwards tells the TinyMCE component which ID
// to use for rendering; since there are two elements with the same ID at that point, it does not work.
// As the Dialog can only contain other controls, we can safely discard the DOM - we cannot do this inside
// the Popup, since it supports displaying arbitrary HTML content.
this.$().remove();
InstanceManager.removeDialogInstance(this);
this.fireAfterClose({origin: this._oCloseTrigger});
};
/**
* Event handler for the focusin event.
* If it occurs on the focus handler elements at the beginning of the dialog, the focus is set to the end, and vice versa.
* @param {jQuery.EventObject} oEvent The event object
* @private
*/
Dialog.prototype.onfocusin = function (oEvent) {
var oSourceDomRef = oEvent.target;
//Check if the invisible FIRST focusable element (suffix '-firstfe') has gained focus
if (oSourceDomRef.id === this.getId() + "-firstfe") {
//Check if buttons are available
var oLastFocusableDomRef = this.$("footer").lastFocusableDomRef() || this.$("cont").lastFocusableDomRef() || (this.getSubHeader() && this.getSubHeader().$().firstFocusableDomRef()) || (this._getAnyHeader() && this._getAnyHeader().$().lastFocusableDomRef());
if (oLastFocusableDomRef) {
jQuery.sap.focus(oLastFocusableDomRef);
}
} else if (oSourceDomRef.id === this.getId() + "-lastfe") {
//Check if the invisible LAST focusable element (suffix '-lastfe') has gained focus
//First check if header content is available
var oFirstFocusableDomRef = (this._getAnyHeader() && this._getAnyHeader().$().firstFocusableDomRef()) || (this.getSubHeader() && this.getSubHeader().$().firstFocusableDomRef()) || this.$("cont").firstFocusableDomRef() || this.$("footer").firstFocusableDomRef();
if (oFirstFocusableDomRef) {
jQuery.sap.focus(oFirstFocusableDomRef);
}
}
};
/* =========================================================== */
/* end: event handlers */
/* =========================================================== */
/* =========================================================== */
/* begin: private functions */
/* =========================================================== */
/**
*
* @param {Object} $Ref
* @param {number} iRealDuration
* @param fnOpened
* @private
*/
Dialog.prototype._openAnimation = function ($Ref, iRealDuration, fnOpened) {
$Ref.addClass("sapMDialogOpen");
if (isTheCurrentBrowserIENine) {
$Ref.fadeIn(200, fnOpened);
} else {
$Ref.css("display", "block");
setTimeout(fnOpened, 210); // the time should be longer the longest transition in the CSS, because of focusing and transition relate issues
}
};
/**
*
* @param {Object} $Ref
* @param {number} iRealDuration
* @param fnClose
* @private
*/
Dialog.prototype._closeAnimation = function ($Ref, iRealDuration, fnClose) {
$Ref.removeClass("sapMDialogOpen");
if (isTheCurrentBrowserIENine) {
$Ref.fadeOut(200, fnClose);
} else {
setTimeout(fnClose, 210);
}
};
/**
*
* @private
*/
Dialog.prototype._setDimensions = function () {
var $this = this.$(),
bStretch = this.getStretch(),
bStretchOnPhone = this.getStretchOnPhone() && sap.ui.Device.system.phone,
bMessageType = this._bMessageType,
oStyles = {};
//the initial size is set in the renderer when the dom is created
if (!bStretch) {
//set the size to the content
if (!this._oManuallySetSize) {
oStyles.width = this.getContentWidth() || undefined;
oStyles.height = this.getContentHeight() || undefined;
} else {
oStyles.width = this._oManuallySetSize.width;
oStyles.height = this._oManuallySetSize.height;
}
}
if ((bStretch && !bMessageType) || (bStretchOnPhone)) {
this.$().addClass('sapMDialogStretched');
}
$this.css(oStyles);
//In Chrome when the dialog is stretched the footer is not rendered in the right position;
if (window.navigator.userAgent.toLowerCase().indexOf("chrome") !== -1 && this.getStretch()) {
//forcing repaint
$this.find('> footer').css({bottom: '0.001px'});
}
};
/**
*
* @private
*/
Dialog.prototype._adjustScrollingPane = function () {
if (this._oScroller) {
this._oScroller.refresh();
}
};
/**
*
* @private
*/
Dialog.prototype._reposition = function () {
};
/**
*
* @private
*/
Dialog.prototype._repositionAfterOpen = function () {
};
/**\
*
* @private
*/
Dialog.prototype._reapplyPosition = function () {
this._adjustScrollingPane();
};
/**
*
* @private
*/
Dialog.prototype._onResize = function () {
if (this.getContentHeight()) {
return;
}
var $dialog = this.$();
var $dialogContent = this.$('cont');
//reset the height so the dialog can grow
$dialogContent.height('auto');
//set the newly calculated size by getting it from the browser rendered layout - by the max-height
var dialogContentHeight = parseInt($dialog.height(), 10) + parseInt($dialog.css("border-top-width"), 10) + parseInt($dialog.css("border-bottom-width"), 10);
$dialogContent.height(dialogContentHeight);
};
/**
*
* @private
*/
Dialog.prototype._createHeader = function () {
if (!this._header) {
// set parent of header to detect changes on title
this._header = new Bar(this.getId() + "-header").addStyleClass("sapMDialogTitle");
this.setAggregation("_header", this._header, false);
}
};
/**
* If a scrollable control (sap.m.NavContainer, sap.m.ScrollContainer, sap.m.Page) is added to dialog's content aggregation as a single child or through one or more sap.ui.mvc.View instances,
* the scrolling inside dialog will be disabled in order to avoid wrapped scrolling areas.
*
* If more than one scrollable control is added to dialog, the scrolling needs to be disabled manually.
* @private
*/
Dialog.prototype._hasSingleScrollableContent = function () {
var aContent = this.getContent(), i;
while (aContent.length === 1 && aContent[0] instanceof sap.ui.core.mvc.View) {
aContent = aContent[0].getContent();
}
if (aContent.length === 1) {
for (i = 0; i < this._scrollContentList.length; i++) {
if (aContent[0] instanceof sap.m[this._scrollContentList[i]]) {
return true;
}
}
}
return false;
};
/**
*
* @private
*/
Dialog.prototype._initBlockLayerAnimation = function () {
this.oPopup._hideBlockLayer = function () {
var $blockLayer = jQuery("#sap-ui-blocklayer-popup");
$blockLayer.removeClass("sapMDialogTransparentBlk");
Popup.prototype._hideBlockLayer.call(this);
};
};
/**
*
* @private
*/
Dialog.prototype._clearBlockLayerAnimation = function () {
if (jQuery.device.is.iphone && !this._bMessageType) {
delete this.oPopup._showBlockLayer;
this.oPopup._hideBlockLayer = function () {
var $blockLayer = jQuery("#sap-ui-blocklayer-popup");
$blockLayer.removeClass("sapMDialogTransparentBlk");
Popup.prototype._hideBlockLayer.call(this);
};
}
};
/**
*
* @private
*/
Dialog.prototype._getFocusId = function () {
// Left or Right button can be visible false and therefore not rendered.
// In such a case, focus should be set somewhere else.
return this.getInitialFocus()
|| this._getFirstFocusableContentSubHeader()
|| this._getFirstFocusableContentElementId()
|| this._getFirstVisibleButtonId()
|| this.getId();
};
/**
*
* @returns {string}
* @private
*/
Dialog.prototype._getFirstVisibleButtonId = function () {
var oBeginButton = this.getBeginButton(),
oEndButton = this.getEndButton(),
aButtons = this.getButtons(),
sButtonId = "";
if (oBeginButton && oBeginButton.getVisible()) {
sButtonId = oBeginButton.getId();
} else if (oEndButton && oEndButton.getVisible()) {
sButtonId = oEndButton.getId();
} else if (aButtons && aButtons.length > 0) {
for (var i = 0; i < aButtons.length; i++) {
if (aButtons[i].getVisible()) {
sButtonId = aButtons[i].getId();
break;
}
}
}
return sButtonId;
};
/**
*
* @returns {string}
* @private
*/
Dialog.prototype._getFirstFocusableContentSubHeader = function () {
var $subHeader = this.$().find('.sapMDialogSubHeader');
var sResult;
var oFirstFocusableDomRef = $subHeader.firstFocusableDomRef();
if (oFirstFocusableDomRef) {
sResult = oFirstFocusableDomRef.id;
}
return sResult;
};
/**
*
* @returns {string}
* @private
*/
Dialog.prototype._getFirstFocusableContentElementId = function () {
var sResult = "";
var $dialogContent = this.$("cont");
var oFirstFocusableDomRef = $dialogContent.firstFocusableDomRef();
if (oFirstFocusableDomRef) {
sResult = oFirstFocusableDomRef.id;
}
return sResult;
};
// The control that needs to be focused after dialog is open is calculated in following sequence:
// initialFocus, first focusable element in content area, beginButton, endButton
// dialog is always modal so the focus doen't need to be on the dialog when there's
// no initialFocus, beginButton and endButton available, but to keep the consistency,
// the focus will in the end fall back to dialog itself.
/**
*
* @private
*/
Dialog.prototype._setInitialFocus = function () {
var sFocusId = this._getFocusId();
var oControl = sap.ui.getCore().byId(sFocusId);
var oFocusDomRef;
if (oControl) {
//if someone tryies to focus an existing but not visible control, focus the Dialog itself.
if (!oControl.getVisible()) {
this.focus();
return;
}
oFocusDomRef = oControl.getFocusDomRef();
}
oFocusDomRef = oFocusDomRef || jQuery.sap.domById(sFocusId);
//if there is no set initial focus, set the default one to the initialFocus association
if (!this.getInitialFocus()) {
this.setAssociation('initialFocus', oFocusDomRef ? oFocusDomRef.id : this.getId(), true);
}
// Setting focus to DOM Element which can open the on screen keyboard on mobile device doesn't work
// consistently across devices. Therefore setting focus to those elements are disabled on mobile devices
// and the keyboard should be opened by the User explicitly
if (sap.ui.Device.system.desktop || (oFocusDomRef && !/input|textarea|select/i.test(oFocusDomRef.tagName))) {
jQuery.sap.focus(oFocusDomRef);
} else {
// Set the focus to the popup itself in order to keep the tab chain
this.focus();
}
};
/**
* Returns the sap.ui.core.ScrollEnablement delegate which is used with this control.
*
* @private
*/
Dialog.prototype.getScrollDelegate = function () {
return this._oScroller;
};
/**
*
* @param {string} sPos
* @returns {string}
* @private
*/
Dialog.prototype._composeAggreNameInHeader = function (sPos) {
var sHeaderAggregationName;
if (sPos === "Begin") {
sHeaderAggregationName = "contentLeft";
} else if (sPos === "End") {
sHeaderAggregationName = "contentRight";
} else {
sHeaderAggregationName = "content" + sPos;
}
return sHeaderAggregationName;
};
/**
*
* @returns {boolean}
* @private
*/
Dialog.prototype._isToolbarEmpty = function () {
// no ToolbarSpacer
var filteredContent = this._oToolbar.getContent().filter(function (content) {
return content.getMetadata().getName() !== 'sap.m.ToolbarSpacer';
});
return filteredContent.length === 0;
};
/**
*
* @param {Object} oButton
* @param {string} sPos
* @param {boolean} bSkipFlag
* @returns {Dialog}
* @private
*/
Dialog.prototype._setButton = function (oButton, sPos, bSkipFlag) {
return this;
};
/**
*
* @param {string} sPos
* @private
*/
Dialog.prototype._getButton = function (sPos) {
var sAggregationName = sPos.toLowerCase() + "Button",
sButtonName = "_o" + this._firstLetterUpperCase(sPos) + "Button";
if (sap.ui.Device.system.phone) {
return this.getAggregation(sAggregationName, null, /*avoid infinite loop*/true);
} else {
return this[sButtonName];
}
};
/**
*
* @param {string} sPos
* @private
*/
Dialog.prototype._getButtonFromHeader = function (sPos) {
if (this._header) {
var sHeaderAggregationName = this._composeAggreNameInHeader(this._firstLetterUpperCase(sPos)),
aContent = this._header.getAggregation(sHeaderAggregationName);
return aContent && aContent[0];
} else {
return null;
}
};
/**
*
* @param {string} sValue
* @returns {string}
* @private
*/
Dialog.prototype._firstLetterUpperCase = function (sValue) {
return sValue.charAt(0).toUpperCase() + sValue.slice(1);
};
/**
* Returns the custom header instance when the customHeader aggregation is set. Otherwise it returns the internal managed
* header instance. This method can be called within composite controls which use sap.m.Dialog inside.
*
* @protected
*/
Dialog.prototype._getAnyHeader = function () {
var oCustomHeader = this.getCustomHeader();
if (oCustomHeader) {
return oCustomHeader;
} else {
var bShowHeader = this.getShowHeader();
// if showHeader is set to false and not for standard dialog in iOS in theme sap_mvi, no header.
if (!bShowHeader) {
return null;
}
this._createHeader();
return this._header;
}
};
/**
*
* @private
*/
Dialog.prototype._deregisterResizeHandler = function () {
};
/**
*
* @private
*/
Dialog.prototype._registerResizeHandler = function () {
};
Dialog.prototype._createToolbarButtons = function () {
var toolbar = this._getToolbar();
var buttons = this.getButtons();
var beginButton = this.getBeginButton();
var endButton = this.getEndButton();
toolbar.removeAllContent();
toolbar.addContent(new ToolbarSpacer());
//if there are buttons they should be in the toolbar and the begin and end buttons should not be used
if (buttons && buttons.length) {
buttons.forEach(function (button) {
toolbar.addContent(button);
});
} else {
if (beginButton) {
toolbar.addContent(beginButton);
}
if (endButton) {
toolbar.addContent(endButton);
}
}
};
/*
*
* @returns {*|sap.m.IBar|null}
* @private
*/
Dialog.prototype._getToolbar = function () {
if (!this._oToolbar) {
this._oToolbar = new AssociativeOverflowToolbar(this.getId() + "-footer").addStyleClass("sapMTBNoBorders").applyTagAndContextClassFor("footer");
this._oToolbar._isControlsInfoCached = function () {
return false;
};
this.setAggregation("_toolbar", this._oToolbar);
}
return this._oToolbar;
};
/* =========================================================== */
/* end: private functions */
/* =========================================================== */
/* =========================================================== */
/* begin: setters */
/* =========================================================== */
//Manage "sapMDialogWithSubHeader" class depending on the visibility of the subHeader
//This is because the dialog has content height and width and the box-sizing have to be content-box in
//order to not recalculate the size with js
Dialog.prototype.setSubHeader = function (oControl) {
this.setAggregation("subHeader", oControl);
if (oControl) {
oControl.setVisible = function (isVisible) {
this.$().toggleClass('sapMDialogWithSubHeader', isVisible);
oControl.setProperty("visible", isVisible);
}.bind(this);
}
return oControl;
};
//The public setters and getters should not be documented via JSDoc because they will appear in the explored app
Dialog.prototype.setLeftButton = function (vButton) {
if (!(vButton instanceof sap.m.Button)) {
vButton = sap.ui.getCore().byId(vButton);
}
//setting leftButton will also set the beginButton with the same button instance.
//as this instance is aggregated by the beginButton, the hidden aggregation isn't needed.
this.setBeginButton(vButton);
return this.setAssociation("leftButton", vButton);
};
Dialog.prototype.setRightButton = function (vButton) {
if (!(vButton instanceof sap.m.Button)) {
vButton = sap.ui.getCore().byId(vButton);
}
//setting rightButton will also set the endButton with the same button instance.
//as this instance is aggregated by the endButton, the hidden aggregation isn't needed.
this.setEndButton(vButton);
return this.setAssociation("rightButton", vButton);
};
Dialog.prototype.getLeftButton = function () {
var oBeginButton = this.getBeginButton();
return oBeginButton ? oBeginButton.getId() : null;
};
Dialog.prototype.getRightButton = function () {
var oEndButton = this.getEndButton();
return oEndButton ? oEndButton.getId() : null;
};
//get buttons should return the buttons, beginButton and endButton aggregations
Dialog.prototype.getAggregation = function (sAggregationName, oDefaultForCreation, bPassBy) {
var originalResponse = Control.prototype.getAggregation.apply(this, Array.prototype.slice.call(arguments, 0, 2));
//if no buttons are set returns the begin and end buttons
if (sAggregationName === 'buttons' && originalResponse.length === 0) {
this.getBeginButton() && originalResponse.push(this.getBeginButton());
this.getEndButton() && originalResponse.push(this.getEndButton());
}
return originalResponse;
};
Dialog.prototype.setTitle = function (sTitle) {
this.setProperty("title", sTitle, true);
if (this._headerTitle) {
this._headerTitle.setText(sTitle);
} else {
this._headerTitle = new sap.m.Title(this.getId() + "-title", {
text: sTitle,
level: "H1"
}).addStyleClass("sapMDialogTitle");
this._createHeader();
this._header.addContentMiddle(this._headerTitle);
}
return this;
};
Dialog.prototype.setCustomHeader = function (oCustomHeader) {
if (oCustomHeader) {
oCustomHeader.addStyleClass("sapMDialogTitle");
}
this.setAggregation("customHeader", oCustomHeader);
};
Dialog.prototype.setState = function (sState) {
var mFlags = {},
$this = this.$(),
sName;
mFlags[sState] = true;
this.setProperty("state", sState, true);
for (sName in Dialog._mStateClasses) {
$this.toggleClass(Dialog._mStateClasses[sName], !!mFlags[sName]);
}
this.setIcon(Dialog._mIcons[sState], true);
};
Dialog.prototype.setIcon = function (sIcon, bInternal) {
if (!bInternal) {
this._externalIcon = sIcon;
} else {
if (this._externalIcon) {
sIcon = this._externalIcon;
}
}
if (sIcon) {
if (sIcon !== this.getIcon()) {
if (this._iconImage) {
this._iconImage.setSrc(sIcon);
} else {
this._iconImage = IconPool.createControlByURI({
id: this.getId() + "-icon",
src: sIcon,
useIconTooltip: false
}, sap.m.Image).addStyleClass("sapMDialogIcon");
this._createHeader();
this._header.insertAggregation("contentMiddle", this._iconImage, 0);
}
}
} else {
var sDialogState = this.getState();
if (!bInternal && sDialogState !== ValueState.None) {
if (this._iconImage) {
this._iconImage.setSrc(Dialog._mIcons[sDialogState]);
}
} else {
if (this._iconImage) {
this._iconImage.destroy();
this._iconImage = null;
}
}
}
this.setProperty("icon", sIcon, true);
return this;
};
Dialog.prototype.setType = function (sType) {
var sOldType = this.getType();
if (sOldType === sType) {
return this;
}
this._bMessageType = (sType === sap.m.DialogType.Message);
return this.setProperty("type", sType, false);
};
Dialog.prototype.setStretch = function (bStretch) {
this._bStretchSet = true;
return this.setProperty("stretch", bStretch);
};
Dialog.prototype.setStretchOnPhone = function (bStretchOnPhone) {
if (this._bStretchSet) {
jQuery.sap.log.warning("sap.m.Dialog: stretchOnPhone property is deprecated. Setting stretchOnPhone property is ignored when there's already stretch property set.");
return this;
}
this.setProperty("stretchOnPhone", bStretchOnPhone);
return this.setProperty("stretch", bStretchOnPhone && sap.ui.Device.system.phone);
};
Dialog.prototype.setVerticalScrolling = function (bValue) {
var oldValue = this.getVerticalScrolling();
if (oldValue === bValue) {
return this;
}
this.$().toggleClass("sapMDialogVerScrollDisabled", !bValue);
this.setProperty("verticalScrolling", bValue);
if (this._oScroller) {
this._oScroller.setVertical(bValue);
}
return this;
};
Dialog.prototype.setHorizontalScrolling = function (bValue) {
var oldValue = this.getHorizontalScrolling();
if (oldValue === bValue) {
return this;
}
this.$().toggleClass("sapMDialogHorScrollDisabled", !bValue);
this.setProperty("horizontalScrolling", bValue);
if (this._oScroller) {
this._oScroller.setHorizontal(bValue);
}
return this;
};
Dialog.prototype.setInitialFocus = function (sInitialFocus) {
// Skip the invalidation when sets the initial focus
//
// The initial focus takes effect after the next open of the dialog, when it's set
// after the dialog is open, the current focus won't be changed
// SelectDialog depends on this. If this has to be changed later, please make sure to
// check the SelectDialog as well where setIntialFocus is called.
return this.setAssociation("initialFocus", sInitialFocus, true);
};
/* =========================================================== */
/* end: setters */
/* =========================================================== */
Dialog.prototype.forceInvalidate = Control.prototype.invalidate;
// stop propagating the invalidate to static UIArea before dialog is opened.
// otherwise the open animation can't be seen
// dialog will be rendered directly to static ui area when the open method is called.
Dialog.prototype.invalidate = function (oOrigin) {
if (this.isOpen()) {
this.forceInvalidate(oOrigin);
}
};
/* =========================================================== */
/* Resize & Drag logic */
/* =========================================================== */
/**
*
* @param {Object} eventTarget
* @returns {boolean}
*/
function isHeaderClicked(eventTarget) {
var $target = jQuery(eventTarget);
var oControl = $target.control(0);
if (!oControl || oControl.getMetadata().getInterfaces().indexOf("sap.m.IBar") > -1) {
return true;
}
return $target.hasClass('sapMDialogTitle');
}
if (sap.ui.Device.system.desktop) {
/**
*
* @param {Object} e
*/
Dialog.prototype.ondblclick = function (e) {
if (isHeaderClicked(e.target)) {
this._bDisableRepositioning = false;
this._oManuallySetPosition = null;
this._oManuallySetSize = null;
//call the reposition
this.oPopup && this.oPopup._applyPosition(this.oPopup._oLastPosition, true);
this._$dialog.removeClass('sapMDialogTouched');
}
};
/**
*
* @param {Object} e
*/
Dialog.prototype.onmousedown = function (e) {
if (e.which === 3) {
return; // on right click don't reposition the dialog
}
if (this.getStretch() || (!this.getDraggable() && !this.getResizable())) {
return;
}
var timeout;
var that = this;
var $w = jQuery(document);
var $target = jQuery(e.target);
var bResize = $target.hasClass('sapMDialogResizeHandler') && this.getResizable();
var fnMouseMoveHandler = function (action) {
timeout = timeout ? clearTimeout(timeout) : setTimeout(function () {
action();
}, 0);
};
var initial = {
x: e.pageX,
y: e.pageY,
width: that._$dialog.width(),
height: that._$dialog.height(),
offset: {
//use e.originalEvent.layerX/Y for Firefox
x: e.offsetX ? e.offsetX : e.originalEvent.layerX,
y: e.offsetY ? e.offsetY : e.originalEvent.layerY
},
position: {
x: that._$dialog.offset().left,
y: that._$dialog.offset().top
}
};
if ((isHeaderClicked(e.target) && this.getDraggable()) || bResize) {
that._bDisableRepositioning = true;
that._$dialog.addClass('sapDialogDisableTransition');
//remove the transform translate
that._$dialog.addClass('sapMDialogTouched');
that._oManuallySetPosition = {
x: initial.position.x,
y: initial.position.y
};
//set the new position of the dialog on mouse down when the transform is disabled by the class
that._$dialog.css({
left: that._oManuallySetPosition.x,
top: that._oManuallySetPosition.y
});
}
if (isHeaderClicked(e.target) && this.getDraggable()) {
$w.on("mousemove.sapMDialog", function (e) {
fnMouseMoveHandler(function () {
that._bDisableRepositioning = true;
that._oManuallySetPosition = {
x: e.pageX - initial.offset.x,
y: e.pageY - initial.offset.y
};
//move the dialog
that._$dialog.css({
left: that._oManuallySetPosition.x,
top: that._oManuallySetPosition.y
});
});
});
} else if (bResize) {
that._$dialog.addClass('sapMDialogResizing');
var isInRTLMode = sap.ui.getCore().getConfiguration().getRTL();
var styles = {};
var minWidth = parseInt(that._$dialog.css('min-width'), 10);
var maxLeftOffset = initial.x + initial.width - minWidth;
$w.on("mousemove.sapMDialog", function (e) {
fnMouseMoveHandler(function () {
that._bDisableRepositioning = true;
that._oManuallySetSize = {
width: initial.width + e.pageX - initial.x,
height: initial.height + e.pageY - initial.y
};
if (isInRTLMode) {
styles.left = Math.min(Math.max(e.pageX, 0), maxLeftOffset);
that._oManuallySetSize.width = initial.width + initial.x - Math.max(e.pageX, 0);
}
styles.width = that._oManuallySetSize.width;
styles.height = that._oManuallySetSize.height;
that._$dialog.css(styles);
});
});
} else {
return;
}
$w.on("mouseup.sapMDialog", function () {
$w.off("mouseup.sapMDialog, mousemove.sapMDialog");
if (bResize) {
that._$dialog.removeClass('sapMDialogResizing');
}
});
e.preventDefault();
e.stopPropagation();
};
}
return Dialog;
}, /* bExport= */ true);
| [INTERNAL] sap.m.Dialog: the content will no longer have size
Change-Id: I618b2f8d6d557ee7d0db5d83f3c44931f449d809
| src/sap.m/src/sap/m/Dialog.js | [INTERNAL] sap.m.Dialog: the content will no longer have size | <ide><path>rc/sap.m/src/sap/m/Dialog.js
<ide>
<ide> oPopup.open();
<ide>
<del> //resize handler ===========================================================================================
<del> var __delayTimer;
<del> jQuery(window).on('resize.sapMDialogWindowResize', function () {
<del> if (__delayTimer) {
<del> __delayTimer = clearTimeout(__delayTimer);
<del> }
<del>
<del> __delayTimer = setTimeout(this._onResize.bind(this), 50);
<del> }.bind(this));
<del>
<del> //set the content size so the scroller can work properly
<del> this._onResize();
<del>
<ide> InstanceManager.addDialogInstance(this);
<ide> return this;
<ide> };
<ide>
<ide> /**
<ide> *
<add> *
<ide> * @private
<ide> */
<ide> Dialog.prototype._onResize = function () {
<del> if (this.getContentHeight()) {
<del> return;
<del> }
<del>
<del> var $dialog = this.$();
<del> var $dialogContent = this.$('cont');
<del>
<del> //reset the height so the dialog can grow
<del> $dialogContent.height('auto');
<del> //set the newly calculated size by getting it from the browser rendered layout - by the max-height
<del> var dialogContentHeight = parseInt($dialog.height(), 10) + parseInt($dialog.css("border-top-width"), 10) + parseInt($dialog.css("border-bottom-width"), 10);
<del> $dialogContent.height(dialogContentHeight);
<ide> };
<ide>
<ide> /** |
|
JavaScript | apache-2.0 | 330452f1f01ecab2e5f60de0f33321f21ba49730 | 0 | netfishx/new_react_rockstar | 0951391c-2f85-11e5-88e8-34363bc765d8 | hello.js | 09495c92-2f85-11e5-938c-34363bc765d8 | 0951391c-2f85-11e5-88e8-34363bc765d8 | hello.js | 0951391c-2f85-11e5-88e8-34363bc765d8 | <ide><path>ello.js
<del>09495c92-2f85-11e5-938c-34363bc765d8
<add>0951391c-2f85-11e5-88e8-34363bc765d8 |
|
Java | apache-2.0 | 2cd92a82e79595e22d2da53ac288e73b6d897876 | 0 | graben/activemq-artemis,tabish121/activemq-artemis,TomRoss/activemq-artemis,apache/activemq-artemis,apache/activemq-artemis,clebertsuconic/activemq-artemis,apache/activemq-artemis,TomRoss/activemq-artemis,graben/activemq-artemis,apache/activemq-artemis,tabish121/activemq-artemis,TomRoss/activemq-artemis,tabish121/activemq-artemis,graben/activemq-artemis,graben/activemq-artemis,clebertsuconic/activemq-artemis,clebertsuconic/activemq-artemis,TomRoss/activemq-artemis,tabish121/activemq-artemis,clebertsuconic/activemq-artemis | /*
* 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.activemq.artemis.protocol.amqp.broker;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.SimpleType;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQPropertyConversionException;
import org.apache.activemq.artemis.api.core.ICoreMessage;
import org.apache.activemq.artemis.api.core.JsonUtil;
import org.apache.activemq.artemis.api.core.RefCountMessage;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.message.openmbean.CompositeDataConstants;
import org.apache.activemq.artemis.core.message.openmbean.MessageOpenTypeFactory;
import org.apache.activemq.artemis.core.paging.PagingStore;
import org.apache.activemq.artemis.core.persistence.CoreMessageObjectPools;
import org.apache.activemq.artemis.core.persistence.Persister;
import org.apache.activemq.artemis.core.server.MessageReference;
import org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageIdHelper;
import org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport;
import org.apache.activemq.artemis.protocol.amqp.converter.AmqpCoreConverter;
import org.apache.activemq.artemis.protocol.amqp.util.NettyReadable;
import org.apache.activemq.artemis.protocol.amqp.util.NettyWritable;
import org.apache.activemq.artemis.protocol.amqp.util.TLSEncode;
import org.apache.activemq.artemis.reader.MessageUtil;
import org.apache.activemq.artemis.utils.ByteUtil;
import org.apache.activemq.artemis.utils.collections.TypedProperties;
import org.apache.qpid.proton.amqp.Binary;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.UnsignedByte;
import org.apache.qpid.proton.amqp.UnsignedInteger;
import org.apache.qpid.proton.amqp.UnsignedLong;
import org.apache.qpid.proton.amqp.UnsignedShort;
import org.apache.qpid.proton.amqp.messaging.AmqpSequence;
import org.apache.qpid.proton.amqp.messaging.AmqpValue;
import org.apache.qpid.proton.amqp.messaging.ApplicationProperties;
import org.apache.qpid.proton.amqp.messaging.Data;
import org.apache.qpid.proton.amqp.messaging.DeliveryAnnotations;
import org.apache.qpid.proton.amqp.messaging.Footer;
import org.apache.qpid.proton.amqp.messaging.Header;
import org.apache.qpid.proton.amqp.messaging.MessageAnnotations;
import org.apache.qpid.proton.amqp.messaging.Properties;
import org.apache.qpid.proton.amqp.messaging.Section;
import org.apache.qpid.proton.codec.DecoderImpl;
import org.apache.qpid.proton.codec.DroppingWritableBuffer;
import org.apache.qpid.proton.codec.ReadableBuffer;
import org.apache.qpid.proton.codec.TypeConstructor;
import org.apache.qpid.proton.codec.WritableBuffer;
import org.apache.qpid.proton.message.Message;
import org.apache.qpid.proton.message.impl.MessageImpl;
import org.jboss.logging.Logger;
import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.getCharsetForTextualContent;
/**
* See <a href="https://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#section-message-format">AMQP v1.0 message format</a>
* <pre>
*
* Bare Message
* |
* .---------------------+--------------------.
* | |
* +--------+-------------+-------------+------------+--------------+--------------+--------+
* | header | delivery- | message- | properties | application- | application- | footer |
* | | annotations | annotations | | properties | data | |
* +--------+-------------+-------------+------------+--------------+--------------+--------+
* | |
* '-------------------------------------------+--------------------------------------------'
* |
* Annotated Message
* </pre>
* <ul>
* <li>Zero or one header sections.
* <li>Zero or one delivery-annotation sections.
* <li>Zero or one message-annotation sections.
* <li>Zero or one properties sections.
* <li>Zero or one application-properties sections.
* <li>The body consists of one of the following three choices:
* <ul>
* <li>one or more data sections
* <li>one or more amqp-sequence sections
* <li>or a single amqp-value section.
* </ul>
* <li>Zero or one footer sections.
* </ul>
*/
public abstract class AMQPMessage extends RefCountMessage implements org.apache.activemq.artemis.api.core.Message {
private static final SimpleString ANNOTATION_AREA_PREFIX = SimpleString.toSimpleString("m.");
protected static final Logger logger = Logger.getLogger(AMQPMessage.class);
public static final SimpleString ADDRESS_PROPERTY = SimpleString.toSimpleString("_AMQ_AD");
// used to perform quick search
private static final Symbol[] SCHEDULED_DELIVERY_SYMBOLS = new Symbol[]{
AMQPMessageSupport.SCHEDULED_DELIVERY_TIME, AMQPMessageSupport.SCHEDULED_DELIVERY_DELAY};
private static final KMPNeedle[] SCHEDULED_DELIVERY_NEEDLES = new KMPNeedle[]{
AMQPMessageSymbolSearch.kmpNeedleOf(AMQPMessageSupport.SCHEDULED_DELIVERY_TIME),
AMQPMessageSymbolSearch.kmpNeedleOf(AMQPMessageSupport.SCHEDULED_DELIVERY_DELAY)};
private static final KMPNeedle[] DUPLICATE_ID_NEEDLES = new KMPNeedle[] {
AMQPMessageSymbolSearch.kmpNeedleOf(org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString())
};
public static final int DEFAULT_MESSAGE_FORMAT = 0;
public static final int DEFAULT_MESSAGE_PRIORITY = 4;
public static final int MAX_MESSAGE_PRIORITY = 9;
protected static final int VALUE_NOT_PRESENT = -1;
/**
* This has been made public just for testing purposes: it's not stable
* and developers shouldn't rely on this for developing purposes.
*/
public enum MessageDataScanningStatus {
NOT_SCANNED(0), RELOAD_PERSISTENCE(1), SCANNED(2);
private static final MessageDataScanningStatus[] STATES;
static {
// this prevent codes to be assigned with the wrong order
// and ensure valueOf to work fine
final MessageDataScanningStatus[] states = values();
STATES = new MessageDataScanningStatus[states.length];
for (final MessageDataScanningStatus state : states) {
final int code = state.code;
if (STATES[code] != null) {
throw new AssertionError("code already in use: " + code);
}
STATES[code] = state;
}
}
final byte code;
MessageDataScanningStatus(int code) {
assert code >= 0 && code <= Byte.MAX_VALUE;
this.code = (byte) code;
}
static MessageDataScanningStatus valueOf(int code) {
checkCode(code);
return STATES[code];
}
private static void checkCode(int code) {
if (code < 0 || code > (STATES.length - 1)) {
throw new IllegalArgumentException("invalid status code: " + code);
}
}
}
// Buffer and state for the data backing this message.
protected byte messageDataScanned = MessageDataScanningStatus.NOT_SCANNED.code;
// Marks the message as needed to be re-encoded to update the backing buffer
protected boolean modified;
// Track locations of the message sections for later use and track the size
// of the header and delivery annotations if present so we can easily exclude
// the delivery annotations later and perform efficient encodes or copies.
protected int headerPosition = VALUE_NOT_PRESENT;
protected int encodedHeaderSize;
protected int deliveryAnnotationsPosition = VALUE_NOT_PRESENT;
protected int encodedDeliveryAnnotationsSize;
protected int messageAnnotationsPosition = VALUE_NOT_PRESENT;
protected int propertiesPosition = VALUE_NOT_PRESENT;
protected int applicationPropertiesPosition = VALUE_NOT_PRESENT;
protected int remainingBodyPosition = VALUE_NOT_PRESENT;
// Message level meta data
protected final long messageFormat;
protected long messageID;
protected SimpleString address;
protected volatile int memoryEstimate = -1;
protected long expiration;
protected boolean expirationReload = false;
protected long scheduledTime = -1;
// The Proton based AMQP message section that are retained in memory, these are the
// mutable portions of the Message as the broker sees it, although AMQP defines that
// the Properties and ApplicationProperties are immutable so care should be taken
// here when making changes to those Sections.
protected Header header;
protected MessageAnnotations messageAnnotations;
protected Properties properties;
protected ApplicationProperties applicationProperties;
protected String connectionID;
protected final CoreMessageObjectPools coreMessageObjectPools;
protected Set<Object> rejectedConsumers;
protected DeliveryAnnotations deliveryAnnotationsForSendBuffer;
protected DeliveryAnnotations deliveryAnnotations;
// These are properties set at the broker level and carried only internally by broker storage.
protected volatile TypedProperties extraProperties;
private volatile Object owner;
/**
* Creates a new {@link AMQPMessage} instance from binary encoded message data.
*
* @param messageFormat
* The Message format tag given the in Transfer that carried this message
* @param extraProperties
* Broker specific extra properties that should be carried with this message
*/
public AMQPMessage(long messageFormat, TypedProperties extraProperties, CoreMessageObjectPools coreMessageObjectPools) {
this.messageFormat = messageFormat;
this.coreMessageObjectPools = coreMessageObjectPools;
this.extraProperties = extraProperties == null ? null : new TypedProperties(extraProperties);
}
protected AMQPMessage(AMQPMessage copy) {
this(copy.messageFormat, copy.extraProperties, copy.coreMessageObjectPools);
this.headerPosition = copy.headerPosition;
this.encodedHeaderSize = copy.encodedHeaderSize;
this.header = copy.header == null ? null : new Header(copy.header);
this.deliveryAnnotationsPosition = copy.deliveryAnnotationsPosition;
this.encodedDeliveryAnnotationsSize = copy.encodedDeliveryAnnotationsSize;
this.deliveryAnnotations = copy.deliveryAnnotations == null ? null : new DeliveryAnnotations(copy.deliveryAnnotations.getValue());
this.messageAnnotationsPosition = copy.messageAnnotationsPosition;
this.messageAnnotations = copy.messageAnnotations == null ? null : new MessageAnnotations(copy.messageAnnotations.getValue());
this.propertiesPosition = copy.propertiesPosition;
this.properties = copy.properties == null ? null : new Properties(copy.properties);
this.applicationPropertiesPosition = copy.applicationPropertiesPosition;
this.applicationProperties = copy.applicationProperties == null ? null : new ApplicationProperties(copy.applicationProperties.getValue());
this.remainingBodyPosition = copy.remainingBodyPosition;
this.messageDataScanned = copy.messageDataScanned;
}
protected AMQPMessage(long messageFormat) {
this.messageFormat = messageFormat;
this.coreMessageObjectPools = null;
}
@Override
public String getProtocolName() {
return ProtonProtocolManagerFactory.AMQP_PROTOCOL_NAME;
}
public final MessageDataScanningStatus getDataScanningStatus() {
return MessageDataScanningStatus.valueOf(messageDataScanned);
}
/** This will return application properties without attempting to decode it.
* That means, if applicationProperties were never parsed before, this will return null, even if there is application properties.
* This was created as an internal method for testing, as we need to validate if the application properties are not decoded until needed. */
protected ApplicationProperties getDecodedApplicationProperties() {
return applicationProperties;
}
protected MessageAnnotations getDecodedMessageAnnotations() {
return messageAnnotations;
}
protected abstract ReadableBuffer getData();
// Access to the AMQP message data using safe copies freshly decoded from the current
// AMQP message data stored in this message wrapper. Changes to these values cannot
// be used to influence the underlying AMQP message data, the standard AMQPMessage API
// must be used to make changes to mutable portions of the message.
/**
* Creates and returns a Proton-J MessageImpl wrapper around the message data. Changes to
* the returned Message are not reflected in this message.
*
* @return a MessageImpl that wraps the AMQP message data in this {@link AMQPMessage}
*/
public final MessageImpl getProtonMessage() {
if (getData() == null) {
throw new NullPointerException("Data is not initialized");
}
ensureScanning();
MessageImpl protonMessage = null;
if (getData() != null) {
protonMessage = (MessageImpl) Message.Factory.create();
getData().rewind();
protonMessage.decode(getData().duplicate());
}
return protonMessage;
}
@Override
public Object getObjectPropertyForFilter(SimpleString key) {
if (key.startsWith(ANNOTATION_AREA_PREFIX)) {
key = key.subSeq(ANNOTATION_AREA_PREFIX.length(), key.length());
return getAnnotation(key);
}
Object value = getObjectProperty(key);
if (value == null) {
TypedProperties extra = getExtraProperties();
if (extra != null) {
value = extra.getProperty(key);
}
}
return value;
}
/**
* Returns a copy of the message Header if one is present, changes to the returned
* Header instance do not affect the original Message.
*
* @return a copy of the Message Header if one exists or null if none present.
*/
public final Header getHeader() {
ensureScanning();
return scanForMessageSection(headerPosition, Header.class);
}
/** Returns the current already scanned header. */
final Header getCurrentHeader() {
return header;
}
/** Return the current already scanned properties.*/
final Properties getCurrentProperties() {
return properties;
}
protected void ensureScanning() {
ensureDataIsValid();
ensureMessageDataScanned();
}
Object getDeliveryAnnotationProperty(Symbol symbol) {
DeliveryAnnotations daToUse = deliveryAnnotations;
if (daToUse == null) {
daToUse = getDeliveryAnnotations();
}
if (daToUse == null) {
return null;
} else {
return daToUse.getValue().get(symbol);
}
}
/**
* Returns a copy of the MessageAnnotations in the message if present or null. Changes to the
* returned DeliveryAnnotations instance do not affect the original Message.
*
* @return a copy of the {@link DeliveryAnnotations} present in the message or null if non present.
*/
public final DeliveryAnnotations getDeliveryAnnotations() {
ensureScanning();
return scanForMessageSection(deliveryAnnotationsPosition, DeliveryAnnotations.class);
}
/**
* Sets the delivery annotations to be included when encoding the message for sending it on the wire.
*
* The broker can add additional message annotations as long as the annotations being added follow the
* rules from the spec. If the user adds something that the remote doesn't understand and it is not
* prefixed with "x-opt" the remote can just kill the link. See:
*
* http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-annotations
*
* @deprecated use MessageReference.setProtocolData(deliveryAnnotations)
* @param deliveryAnnotations delivery annotations used in the sendBuffer() method
*/
@Deprecated
public final void setDeliveryAnnotationsForSendBuffer(DeliveryAnnotations deliveryAnnotations) {
this.deliveryAnnotationsForSendBuffer = deliveryAnnotations;
}
/**
* Returns a copy of the DeliveryAnnotations in the message if present or null. Changes to the
* returned MessageAnnotations instance do not affect the original Message.
*
* @return a copy of the {@link MessageAnnotations} present in the message or null if non present.
*/
public final MessageAnnotations getMessageAnnotations() {
ensureScanning();
return scanForMessageSection(messageAnnotationsPosition, MessageAnnotations.class);
}
/**
* Returns a copy of the message Properties if one is present, changes to the returned
* Properties instance do not affect the original Message.
*
* @return a copy of the Message Properties if one exists or null if none present.
*/
public final Properties getProperties() {
ensureScanning();
return scanForMessageSection(propertiesPosition, Properties.class);
}
/**
* Returns a copy of the {@link ApplicationProperties} present in the message if present or null.
* Changes to the returned MessageAnnotations instance do not affect the original Message.
*
* @return a copy of the {@link ApplicationProperties} present in the message or null if non present.
*/
public final ApplicationProperties getApplicationProperties() {
ensureScanning();
return scanForMessageSection(applicationPropertiesPosition, ApplicationProperties.class);
}
/** This is different from toString, as this will print an expanded version of the buffer
* in Hex and programmers's readable format */
public final String toDebugString() {
return ByteUtil.debugByteArray(getData().array());
}
/**
* Retrieves the AMQP Section that composes the body of this message by decoding a
* fresh copy from the encoded message data. Changes to the returned value are not
* reflected in the value encoded in the original message.
*
* @return the Section that makes up the body of this message.
*/
public final Section getBody() {
ensureScanning();
// We only handle Sections of AmqpSequence, AmqpValue and Data types so we filter on those.
// There could also be a Footer and no body so this will prevent a faulty return type in case
// of no body or message type we don't handle.
return scanForMessageSection(Math.max(0, remainingBodyPosition), AmqpSequence.class, AmqpValue.class, Data.class);
}
/**
* Retrieves the AMQP Footer encoded in the data of this message by decoding a
* fresh copy from the encoded message data. Changes to the returned value are not
* reflected in the value encoded in the original message.
*
* @return the Footer that was encoded into this AMQP Message.
*/
public final Footer getFooter() {
ensureScanning();
return scanForMessageSection(Math.max(0, remainingBodyPosition), Footer.class);
}
protected <T> T scanForMessageSection(int scanStartPosition, Class...targetTypes) {
return scanForMessageSection(getData().duplicate().position(0), scanStartPosition, targetTypes);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected <T> T scanForMessageSection(ReadableBuffer buffer, int scanStartPosition, Class...targetTypes) {
ensureMessageDataScanned();
// In cases where we parsed out enough to know the value is not encoded in the message
// we can exit without doing any reads or buffer hopping.
if (scanStartPosition == VALUE_NOT_PRESENT) {
return null;
}
final DecoderImpl decoder = TLSEncode.getDecoder();
buffer.position(scanStartPosition);
T section = null;
decoder.setBuffer(buffer);
try {
while (buffer.hasRemaining()) {
TypeConstructor<?> constructor = decoder.readConstructor();
for (Class<?> type : targetTypes) {
if (type.equals(constructor.getTypeClass())) {
section = (T) constructor.readValue();
return section;
}
}
constructor.skipValue();
}
} finally {
decoder.setBuffer(null);
}
return section;
}
protected ApplicationProperties lazyDecodeApplicationProperties() {
ensureMessageDataScanned();
if (applicationProperties != null || applicationPropertiesPosition == VALUE_NOT_PRESENT) {
return applicationProperties;
}
return lazyDecodeApplicationProperties(getData().duplicate().position(0));
}
protected ApplicationProperties lazyDecodeApplicationProperties(ReadableBuffer data) {
if (applicationProperties == null && applicationPropertiesPosition != VALUE_NOT_PRESENT) {
applicationProperties = scanForMessageSection(data, applicationPropertiesPosition, ApplicationProperties.class);
if (owner != null && memoryEstimate != -1) {
// the memory has already been tracked and needs to be updated to reflect the new decoding
int addition = unmarshalledApplicationPropertiesMemoryEstimateFromData(data);
((PagingStore)owner).addSize(addition, false);
final int updatedEstimate = memoryEstimate + addition;
memoryEstimate = updatedEstimate;
}
}
return applicationProperties;
}
protected int unmarshalledApplicationPropertiesMemoryEstimateFromData(ReadableBuffer data) {
if (applicationProperties != null) {
// they have been unmarshalled, estimate memory usage based on their encoded size
if (remainingBodyPosition != VALUE_NOT_PRESENT) {
return remainingBodyPosition - applicationPropertiesPosition;
} else {
return data.capacity() - applicationPropertiesPosition;
}
}
return 0;
}
@SuppressWarnings("unchecked")
protected Map<String, Object> getApplicationPropertiesMap(boolean createIfAbsent) {
ApplicationProperties appMap = lazyDecodeApplicationProperties();
Map<String, Object> map = null;
if (appMap != null) {
map = appMap.getValue();
}
if (map == null) {
if (createIfAbsent) {
map = new HashMap<>();
this.applicationProperties = new ApplicationProperties(map);
} else {
map = Collections.EMPTY_MAP;
}
}
return map;
}
@SuppressWarnings("unchecked")
protected Map<Symbol, Object> getMessageAnnotationsMap(boolean createIfAbsent) {
Map<Symbol, Object> map = null;
if (messageAnnotations != null) {
map = messageAnnotations.getValue();
}
if (map == null) {
if (createIfAbsent) {
map = new HashMap<>();
this.messageAnnotations = new MessageAnnotations(map);
} else {
map = Collections.EMPTY_MAP;
}
}
return map;
}
protected Object getMessageAnnotation(String annotation) {
Object messageAnnotation = getMessageAnnotation(Symbol.getSymbol(AMQPMessageSupport.toAnnotationName(annotation)));
if (messageAnnotation == null) {
messageAnnotation = getMessageAnnotation(Symbol.getSymbol(annotation));
}
return messageAnnotation;
}
protected Object getMessageAnnotation(Symbol annotation) {
return getMessageAnnotationsMap(false).get(annotation);
}
protected Object removeMessageAnnotation(Symbol annotation) {
return getMessageAnnotationsMap(false).remove(annotation);
}
protected void setMessageAnnotation(String annotation, Object value) {
setMessageAnnotation(Symbol.getSymbol(annotation), value);
}
protected void setMessageAnnotation(Symbol annotation, Object value) {
if (value instanceof SimpleString) {
value = value.toString();
}
getMessageAnnotationsMap(true).put(annotation, value);
}
protected void setMessageAnnotations(MessageAnnotations messageAnnotations) {
this.messageAnnotations = messageAnnotations;
}
// Message decoding and copying methods. Care must be taken here to ensure the buffer and the
// state tracking information is kept up to data. When the message is manually changed a forced
// re-encode should be done to update the backing data with the in memory elements.
protected synchronized void ensureMessageDataScanned() {
final MessageDataScanningStatus state = getDataScanningStatus();
switch (state) {
case NOT_SCANNED:
scanMessageData();
break;
case RELOAD_PERSISTENCE:
lazyScanAfterReloadPersistence();
break;
case SCANNED:
// NO-OP
break;
}
}
protected int getEstimateSavedEncode() {
return remainingBodyPosition > 0 ? remainingBodyPosition : 1024;
}
protected synchronized void resetMessageData() {
header = null;
messageAnnotations = null;
properties = null;
applicationProperties = null;
if (!expirationReload) {
expiration = 0;
}
encodedHeaderSize = 0;
memoryEstimate = -1;
scheduledTime = -1;
encodedDeliveryAnnotationsSize = 0;
headerPosition = VALUE_NOT_PRESENT;
deliveryAnnotationsPosition = VALUE_NOT_PRESENT;
propertiesPosition = VALUE_NOT_PRESENT;
applicationPropertiesPosition = VALUE_NOT_PRESENT;
remainingBodyPosition = VALUE_NOT_PRESENT;
}
protected synchronized void scanMessageData() {
scanMessageData(getData());
}
protected synchronized void scanMessageData(ReadableBuffer data) {
DecoderImpl decoder = TLSEncode.getDecoder();
decoder.setBuffer(data);
resetMessageData();
try {
while (data.hasRemaining()) {
int constructorPos = data.position();
TypeConstructor<?> constructor = decoder.readConstructor();
if (Header.class.equals(constructor.getTypeClass())) {
header = (Header) constructor.readValue();
headerPosition = constructorPos;
encodedHeaderSize = data.position();
if (header.getTtl() != null) {
if (!expirationReload) {
expiration = System.currentTimeMillis() + header.getTtl().intValue();
}
}
} else if (DeliveryAnnotations.class.equals(constructor.getTypeClass())) {
deliveryAnnotationsPosition = constructorPos;
this.deliveryAnnotations = (DeliveryAnnotations) constructor.readValue();
encodedDeliveryAnnotationsSize = data.position() - constructorPos;
} else if (MessageAnnotations.class.equals(constructor.getTypeClass())) {
messageAnnotationsPosition = constructorPos;
messageAnnotations = (MessageAnnotations) constructor.readValue();
} else if (Properties.class.equals(constructor.getTypeClass())) {
propertiesPosition = constructorPos;
properties = (Properties) constructor.readValue();
if (properties.getAbsoluteExpiryTime() != null && properties.getAbsoluteExpiryTime().getTime() > 0) {
if (!expirationReload) {
expiration = properties.getAbsoluteExpiryTime().getTime();
}
}
} else if (ApplicationProperties.class.equals(constructor.getTypeClass())) {
// Lazy decoding will start at the TypeConstructor of these ApplicationProperties
// but we scan past it to grab the location of the possible body and footer section.
applicationPropertiesPosition = constructorPos;
constructor.skipValue();
remainingBodyPosition = data.hasRemaining() ? data.position() : VALUE_NOT_PRESENT;
break;
} else {
// This will be either the body or a Footer section which will be treated as an immutable
// and be copied as is when re-encoding the message.
remainingBodyPosition = constructorPos;
break;
}
}
} finally {
decoder.setBuffer(null);
data.rewind();
}
this.messageDataScanned = MessageDataScanningStatus.SCANNED.code;
}
@Override
public abstract org.apache.activemq.artemis.api.core.Message copy();
// Core Message APIs for persisting and encoding of message data along with
// utilities for checking memory usage and encoded size characteristics.
/**
* Would be called by the Artemis Core components to encode the message into
* the provided send buffer. Because of how Proton message data handling works
* this method is not currently used by the AMQP protocol head and will not be
* called for out-bound sends.
*
* @see #getSendBuffer(int, MessageReference) for the actual method used for message sends.
*/
@Override
public final void sendBuffer(ByteBuf buffer, int deliveryCount) {
ensureDataIsValid();
NettyWritable writable = new NettyWritable(buffer);
writable.put(getSendBuffer(deliveryCount, null));
}
/**
* Gets a ByteBuf from the Message that contains the encoded bytes to be sent on the wire.
* <p>
* When possible this method will present the bytes to the caller without copying them into
* a new buffer copy. If copying is needed a new Netty buffer is created and returned. The
* caller should ensure that the reference count on the returned buffer is always decremented
* to avoid a leak in the case of a copied buffer being returned.
*
* @param deliveryCount
* The new delivery count for this message.
*
* @return a Netty ByteBuf containing the encoded bytes of this Message instance.
*/
public ReadableBuffer getSendBuffer(int deliveryCount, MessageReference reference) {
ensureDataIsValid();
DeliveryAnnotations daToWrite;
if (reference != null && reference.getProtocolData() instanceof DeliveryAnnotations) {
daToWrite = (DeliveryAnnotations) reference.getProtocolData();
} else {
// deliveryAnnotationsForSendBuffer was an old API form where a deliver could set it before deliver
daToWrite = deliveryAnnotationsForSendBuffer;
}
if (deliveryCount > 1 || daToWrite != null || deliveryAnnotationsPosition != VALUE_NOT_PRESENT) {
return createDeliveryCopy(deliveryCount, daToWrite);
} else {
// Common case message has no delivery annotations, no delivery annotations for the send buffer were set
// and this is the first delivery so no re-encoding or section skipping needed.
return getData().duplicate();
}
}
/** it will create a copy with the relevant delivery annotation and its copy */
protected ReadableBuffer createDeliveryCopy(int deliveryCount, DeliveryAnnotations deliveryAnnotations) {
ReadableBuffer duplicate = getData().duplicate();
final int amqpDeliveryCount = deliveryCount - 1;
final ByteBuf result = PooledByteBufAllocator.DEFAULT.heapBuffer(getEncodeSize());
// If this is re-delivering the message then the header must be re-encoded
// otherwise we want to write the original header if present. When a
// Header is present we need to copy it as we are updating the re-delivered
// message and not the stored version which we don't want to invalidate here.
Header localHeader = this.header;
if (localHeader == null) {
if (deliveryCount > 1) {
localHeader = new Header();
}
} else {
localHeader = new Header(header);
}
if (localHeader != null) {
localHeader.setDeliveryCount(UnsignedInteger.valueOf(amqpDeliveryCount));
TLSEncode.getEncoder().setByteBuffer(new NettyWritable(result));
TLSEncode.getEncoder().writeObject(localHeader);
TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null);
}
writeDeliveryAnnotationsForSendBuffer(result, deliveryAnnotations);
// skip existing delivery annotations of the original message
duplicate.position(encodedHeaderSize + encodedDeliveryAnnotationsSize);
result.writeBytes(duplicate.byteBuffer());
return new NettyReadable(result);
}
protected void writeDeliveryAnnotationsForSendBuffer(ByteBuf result, DeliveryAnnotations deliveryAnnotations) {
if (deliveryAnnotations != null && !deliveryAnnotations.getValue().isEmpty()) {
TLSEncode.getEncoder().setByteBuffer(new NettyWritable(result));
TLSEncode.getEncoder().writeObject(deliveryAnnotations);
TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null);
}
}
protected int getDeliveryAnnotationsForSendBufferSize() {
if (deliveryAnnotationsForSendBuffer == null || deliveryAnnotationsForSendBuffer.getValue().isEmpty()) {
return 0;
}
DroppingWritableBuffer droppingWritableBuffer = new DroppingWritableBuffer();
TLSEncode.getEncoder().setByteBuffer(droppingWritableBuffer);
TLSEncode.getEncoder().writeObject(deliveryAnnotationsForSendBuffer);
TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null);
return droppingWritableBuffer.position() + 1;
}
@Override
public void messageChanged() {
modified = true;
}
@Override
public abstract int getEncodeSize();
@Override
public final void receiveBuffer(ByteBuf buffer) {
// Not used for AMQP messages.
}
@Override
public abstract int getMemoryEstimate();
@Override
public Map<String, Object> toPropertyMap(int valueSizeLimit) {
return toPropertyMap(false, valueSizeLimit);
}
private Map<String, Object> toPropertyMap(boolean expandPropertyType, int valueSizeLimit) {
String extraPropertiesPrefix;
String applicationPropertiesPrefix;
String annotationPrefix;
String propertiesPrefix;
if (expandPropertyType) {
extraPropertiesPrefix = "extraProperties.";
applicationPropertiesPrefix = "applicationProperties.";
annotationPrefix = "messageAnnotations.";
propertiesPrefix = "properties.";
} else {
extraPropertiesPrefix = "";
applicationPropertiesPrefix = "";
annotationPrefix = "";
propertiesPrefix = "";
}
Map map = new HashMap<>();
for (SimpleString name : getPropertyNames()) {
Object value = getObjectProperty(name.toString());
//some property is Binary, which is not available for management console
if (value instanceof Binary) {
value = ((Binary)value).getArray();
}
map.put(applicationPropertiesPrefix + name, JsonUtil.truncate(value, valueSizeLimit));
}
TypedProperties extraProperties = getExtraProperties();
if (extraProperties != null) {
extraProperties.forEach((s, o) -> {
if (o instanceof Number) {
// keep fields like _AMQ_ACTUAL_EXPIRY in their original type
map.put(extraPropertiesPrefix + s.toString(), o);
} else {
map.put(extraPropertiesPrefix + s.toString(), JsonUtil.truncate(o != null ? o.toString() : o, valueSizeLimit));
}
});
}
addAnnotationsAsProperties(annotationPrefix, map, messageAnnotations);
if (properties != null) {
if (properties.getContentType() != null) {
map.put(propertiesPrefix + "contentType", properties.getContentType().toString());
}
if (properties.getContentEncoding() != null) {
map.put(propertiesPrefix + "contentEncoding", properties.getContentEncoding().toString());
}
if (properties.getGroupId() != null) {
map.put(propertiesPrefix + "groupId", properties.getGroupId());
}
if (properties.getGroupSequence() != null) {
map.put(propertiesPrefix + "groupSequence", properties.getGroupSequence().intValue());
}
if (properties.getReplyToGroupId() != null) {
map.put(propertiesPrefix + "replyToGroupId", properties.getReplyToGroupId());
}
if (properties.getCreationTime() != null) {
map.put(propertiesPrefix + "creationTime", properties.getCreationTime().getTime());
}
if (properties.getAbsoluteExpiryTime() != null) {
map.put(propertiesPrefix + "absoluteExpiryTime", properties.getAbsoluteExpiryTime().getTime());
}
if (properties.getTo() != null) {
map.put(propertiesPrefix + "to", properties.getTo());
}
if (properties.getSubject() != null) {
map.put(propertiesPrefix + "subject", properties.getSubject());
}
if (properties.getReplyTo() != null) {
map.put(propertiesPrefix + "replyTo", properties.getReplyTo());
}
}
return map;
}
protected static void addAnnotationsAsProperties(String prefix, Map map, MessageAnnotations annotations) {
if (annotations != null && annotations.getValue() != null) {
for (Map.Entry<?, ?> entry : annotations.getValue().entrySet()) {
String key = entry.getKey().toString();
if ("x-opt-delivery-time".equals(key) && entry.getValue() != null) {
long deliveryTime = ((Number) entry.getValue()).longValue();
map.put(prefix + "x-opt-delivery-time", deliveryTime);
} else if ("x-opt-delivery-delay".equals(key) && entry.getValue() != null) {
long delay = ((Number) entry.getValue()).longValue();
map.put(prefix + "x-opt-delivery-delay", delay);
} else if (AMQPMessageSupport.X_OPT_INGRESS_TIME.equals(key) && entry.getValue() != null) {
map.put(prefix + AMQPMessageSupport.X_OPT_INGRESS_TIME, ((Number) entry.getValue()).longValue());
} else {
try {
map.put(prefix + key, entry.getValue());
} catch (ActiveMQPropertyConversionException e) {
logger.warn(e.getMessage(), e);
}
}
}
}
}
@Override
public ICoreMessage toCore(CoreMessageObjectPools coreMessageObjectPools) {
try {
ensureScanning();
return AmqpCoreConverter.toCore(
this, coreMessageObjectPools, header, messageAnnotations, properties, lazyDecodeApplicationProperties(), getBody(), getFooter());
} catch (Exception e) {
logger.warn(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
public ICoreMessage toCore() {
return toCore(coreMessageObjectPools);
}
@Override
public abstract void persist(ActiveMQBuffer targetRecord);
@Override
public abstract int getPersistSize();
protected int internalPersistSize() {
return getData().remaining();
}
@Override
public abstract void reloadPersistence(ActiveMQBuffer record, CoreMessageObjectPools pools);
protected synchronized void lazyScanAfterReloadPersistence() {
assert messageDataScanned == MessageDataScanningStatus.RELOAD_PERSISTENCE.code;
scanMessageData();
messageDataScanned = MessageDataScanningStatus.SCANNED.code;
modified = false;
// reinitialise memory estimate as message will already be on a queue
// and lazy decode will want to update
getMemoryEstimate();
}
@Override
public abstract long getPersistentSize() throws ActiveMQException;
@Override
public abstract Persister<org.apache.activemq.artemis.api.core.Message> getPersister();
@Override
public abstract void reencode();
protected abstract void ensureDataIsValid();
protected abstract void encodeMessage();
// These methods interact with the Extra Properties that can accompany the message but
// because these are not sent on the wire, update to these does not force a re-encode on
// send of the message.
public final TypedProperties createExtraProperties() {
if (extraProperties == null) {
extraProperties = new TypedProperties(INTERNAL_PROPERTY_NAMES_PREDICATE);
}
return extraProperties;
}
public final TypedProperties getExtraProperties() {
return extraProperties;
}
public final AMQPMessage setExtraProperties(TypedProperties extraProperties) {
this.extraProperties = extraProperties;
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putExtraBytesProperty(SimpleString key, byte[] value) {
createExtraProperties().putBytesProperty(key, value);
return this;
}
@Override
public final byte[] getExtraBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException {
if (extraProperties == null) {
return null;
} else {
return extraProperties.getBytesProperty(key);
}
}
@Override
public void clearInternalProperties() {
if (extraProperties != null) {
extraProperties.clearInternalProperties();
}
}
@Override
public final byte[] removeExtraBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException {
if (extraProperties == null) {
return null;
} else {
return (byte[])extraProperties.removeProperty(key);
}
}
// Message meta data access for Core and AMQP usage.
@Override
public final org.apache.activemq.artemis.api.core.Message setConnectionID(String connectionID) {
this.connectionID = connectionID;
return this;
}
@Override
public final String getConnectionID() {
return connectionID;
}
public final long getMessageFormat() {
return messageFormat;
}
@Override
public final long getMessageID() {
return messageID;
}
@Override
public final org.apache.activemq.artemis.api.core.Message setMessageID(long id) {
this.messageID = id;
return this;
}
@Override
public final long getExpiration() {
if (!expirationReload) {
ensureMessageDataScanned();
}
return expiration;
}
public void reloadExpiration(long expiration) {
this.expiration = expiration;
this.expirationReload = true;
}
@Override
public final AMQPMessage setExpiration(long expiration) {
if (properties != null) {
if (expiration <= 0) {
properties.setAbsoluteExpiryTime(null);
} else {
properties.setAbsoluteExpiryTime(new Date(expiration));
}
} else if (expiration > 0) {
properties = new Properties();
properties.setAbsoluteExpiryTime(new Date(expiration));
}
// We are overriding expiration with an Absolute expiration time so any
// previous Header based TTL also needs to be removed.
if (header != null) {
header.setTtl(null);
}
this.expiration = Math.max(0, expiration);
return this;
}
@Override
public final Object getUserID() {
// User ID in Artemis API means Message ID
if (properties != null && properties.getMessageId() != null) {
return properties.getMessageId();
} else {
return null;
}
}
/**
* Before we added AMQP into Artemis the name getUserID was already taken by JMSMessageID.
* We cannot simply change the names now as it would break the API for existing clients.
*
* This is to return and read the proper AMQP userID.
*
* @return the UserID value in the AMQP Properties if one is present.
*/
public final Object getAMQPUserID() {
if (properties != null && properties.getUserId() != null) {
Binary binary = properties.getUserId();
return new String(binary.getArray(), binary.getArrayOffset(), binary.getLength(), StandardCharsets.UTF_8);
} else {
return null;
}
}
@Override
public final org.apache.activemq.artemis.api.core.Message setUserID(Object userID) {
return this;
}
@Override
public final Object getDuplicateProperty() {
if (applicationProperties == null && messageDataScanned == MessageDataScanningStatus.SCANNED.code && applicationPropertiesPosition != VALUE_NOT_PRESENT) {
if (!AMQPMessageSymbolSearch.anyApplicationProperties(getData(), DUPLICATE_ID_NEEDLES, applicationPropertiesPosition)) {
// no need for duplicate-property
return null;
}
}
return getApplicationObjectProperty(org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString());
}
@Override
public boolean isDurable() {
if (header != null && header .getDurable() != null) {
return header.getDurable();
} else {
// if header == null and scanningStatus=RELOAD_PERSISTENCE, it means the message can only be durable
// even though the parsing hasn't happened yet
return getDataScanningStatus() == MessageDataScanningStatus.RELOAD_PERSISTENCE;
}
}
@Override
public final org.apache.activemq.artemis.api.core.Message setDurable(boolean durable) {
if (header == null) {
header = new Header();
}
header.setDurable(durable); // Message needs to be re-encoded following this action.
return this;
}
@Override
public final String getAddress() {
SimpleString addressSimpleString = getAddressSimpleString();
return addressSimpleString == null ? null : addressSimpleString.toString();
}
@Override
public final AMQPMessage setAddress(String address) {
setAddress(cachedAddressSimpleString(address));
return this;
}
@Override
public final AMQPMessage setAddress(SimpleString address) {
this.address = address;
createExtraProperties().putSimpleStringProperty(ADDRESS_PROPERTY, address);
return this;
}
final void reloadAddress(SimpleString address) {
this.address = address;
}
@Override
public final SimpleString getAddressSimpleString() {
if (address == null) {
TypedProperties extraProperties = getExtraProperties();
// we first check if extraProperties is not null, no need to create it just to check it here
if (extraProperties != null) {
address = extraProperties.getSimpleStringProperty(ADDRESS_PROPERTY);
}
if (address == null) {
// if it still null, it will look for the address on the getTo();
if (properties != null && properties.getTo() != null) {
address = cachedAddressSimpleString(properties.getTo());
}
}
}
return address;
}
protected SimpleString cachedAddressSimpleString(String address) {
return CoreMessageObjectPools.cachedAddressSimpleString(address, coreMessageObjectPools);
}
@Override
public final long getTimestamp() {
if (properties != null && properties.getCreationTime() != null) {
return properties.getCreationTime().getTime();
} else {
return 0L;
}
}
@Override
public final org.apache.activemq.artemis.api.core.Message setTimestamp(long timestamp) {
if (properties == null) {
properties = new Properties();
}
properties.setCreationTime(new Date(timestamp));
return this;
}
@Override
public final byte getPriority() {
if (header != null && header.getPriority() != null) {
return (byte) Math.min(header.getPriority().intValue(), MAX_MESSAGE_PRIORITY);
} else {
return DEFAULT_MESSAGE_PRIORITY;
}
}
@Override
public final org.apache.activemq.artemis.api.core.Message setPriority(byte priority) {
if (header == null) {
header = new Header();
}
header.setPriority(UnsignedByte.valueOf(priority));
return this;
}
@Override
public final SimpleString getReplyTo() {
if (properties != null) {
return SimpleString.toSimpleString(properties.getReplyTo());
} else {
return null;
}
}
@Override
public final AMQPMessage setReplyTo(SimpleString address) {
if (properties == null) {
properties = new Properties();
}
properties.setReplyTo(address != null ? address.toString() : null);
return this;
}
@Override
public final RoutingType getRoutingType() {
ensureMessageDataScanned();
Object routingType = getMessageAnnotation(AMQPMessageSupport.ROUTING_TYPE);
if (routingType != null) {
return RoutingType.getType(((Number) routingType).byteValue());
} else {
routingType = getMessageAnnotation(AMQPMessageSupport.JMS_DEST_TYPE_MSG_ANNOTATION);
if (routingType != null) {
if (AMQPMessageSupport.QUEUE_TYPE == ((Number) routingType).byteValue() || AMQPMessageSupport.TEMP_QUEUE_TYPE == ((Number) routingType).byteValue()) {
return RoutingType.ANYCAST;
} else if (AMQPMessageSupport.TOPIC_TYPE == ((Number) routingType).byteValue() || AMQPMessageSupport.TEMP_TOPIC_TYPE == ((Number) routingType).byteValue()) {
return RoutingType.MULTICAST;
}
} else {
return null;
}
return null;
}
}
@Override
public final org.apache.activemq.artemis.api.core.Message setRoutingType(RoutingType routingType) {
if (routingType == null) {
removeMessageAnnotation(AMQPMessageSupport.ROUTING_TYPE);
} else {
setMessageAnnotation(AMQPMessageSupport.ROUTING_TYPE, routingType.getType());
}
return this;
}
@Override
public final SimpleString getGroupID() {
ensureMessageDataScanned();
if (properties != null && properties.getGroupId() != null) {
return SimpleString.toSimpleString(properties.getGroupId(),
coreMessageObjectPools == null ? null : coreMessageObjectPools.getGroupIdStringSimpleStringPool());
} else {
return null;
}
}
@Override
public final int getGroupSequence() {
ensureMessageDataScanned();
if (properties != null && properties.getGroupSequence() != null) {
return properties.getGroupSequence().intValue();
} else {
return 0;
}
}
@Override
public final Object getCorrelationID() {
return properties != null ? properties.getCorrelationId() : null;
}
@Override
public final org.apache.activemq.artemis.api.core.Message setCorrelationID(final Object correlationID) {
if (properties == null) {
properties = new Properties();
}
properties.setCorrelationId(correlationID);
return this;
}
@Override
public boolean hasScheduledDeliveryTime() {
if (scheduledTime >= 0) {
return scheduledTime > 0;
}
return anyMessageAnnotations(SCHEDULED_DELIVERY_SYMBOLS, SCHEDULED_DELIVERY_NEEDLES);
}
private boolean anyMessageAnnotations(Symbol[] symbols, KMPNeedle[] symbolNeedles) {
assert symbols.length == symbolNeedles.length;
final int count = symbols.length;
if (messageDataScanned == MessageDataScanningStatus.SCANNED.code) {
final MessageAnnotations messageAnnotations = this.messageAnnotations;
if (messageAnnotations == null) {
return false;
}
Map<Symbol, Object> map = messageAnnotations.getValue();
if (map == null) {
return false;
}
for (int i = 0; i < count; i++) {
if (map.containsKey(symbols[i])) {
return true;
}
}
return false;
}
return AMQPMessageSymbolSearch.anyMessageAnnotations(getData(), symbolNeedles);
}
@Override
public final Long getScheduledDeliveryTime() {
ensureMessageDataScanned();
if (scheduledTime < 0) {
Object objscheduledTime = getMessageAnnotation(AMQPMessageSupport.SCHEDULED_DELIVERY_TIME);
Object objdelay = getMessageAnnotation(AMQPMessageSupport.SCHEDULED_DELIVERY_DELAY);
if (objscheduledTime != null && objscheduledTime instanceof Number) {
this.scheduledTime = ((Number) objscheduledTime).longValue();
} else if (objdelay != null && objdelay instanceof Number) {
this.scheduledTime = System.currentTimeMillis() + ((Number) objdelay).longValue();
} else {
this.scheduledTime = 0;
}
}
return scheduledTime;
}
@Override
public final AMQPMessage setScheduledDeliveryTime(Long time) {
if (time != null && time.longValue() > 0) {
setMessageAnnotation(AMQPMessageSupport.SCHEDULED_DELIVERY_TIME, time);
removeMessageAnnotation(AMQPMessageSupport.SCHEDULED_DELIVERY_DELAY);
scheduledTime = time;
} else {
removeMessageAnnotation(AMQPMessageSupport.SCHEDULED_DELIVERY_TIME);
removeMessageAnnotation(AMQPMessageSupport.SCHEDULED_DELIVERY_DELAY);
scheduledTime = 0;
}
return this;
}
@Override
public final Object removeAnnotation(SimpleString key) {
return removeMessageAnnotation(Symbol.getSymbol(key.toString()));
}
@Override
public final Object getAnnotation(SimpleString key) {
return getMessageAnnotation(key.toString());
}
@Override
public final AMQPMessage setAnnotation(SimpleString key, Object value) {
setMessageAnnotation(key.toString(), value);
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message setBrokerProperty(SimpleString key, Object value) {
// Annotation names have to start with x-opt
setMessageAnnotation(AMQPMessageSupport.toAnnotationName(key.toString()), value);
createExtraProperties().putProperty(key, value);
return this;
}
@Override
public Object getBrokerProperty(SimpleString key) {
TypedProperties extra = getExtraProperties();
if (extra == null) {
return null;
}
return extra.getProperty(key);
}
@Override
public final org.apache.activemq.artemis.api.core.Message setIngressTimestamp() {
setMessageAnnotation(AMQPMessageSupport.INGRESS_TIME_MSG_ANNOTATION, System.currentTimeMillis());
return this;
}
@Override
public Long getIngressTimestamp() {
return (Long) getMessageAnnotation(AMQPMessageSupport.INGRESS_TIME_MSG_ANNOTATION);
}
// JMS Style property access methods. These can result in additional decode of AMQP message
// data from Application properties. Updates to application properties puts the message in a
// dirty state and requires a re-encode of the data to update all buffer state data otherwise
// the next send of the Message will not include changes made here.
@Override
public final Object removeProperty(SimpleString key) {
return removeProperty(key.toString());
}
@Override
public final Object removeProperty(String key) {
return getApplicationPropertiesMap(false).remove(key);
}
@Override
public final boolean containsProperty(SimpleString key) {
return containsProperty(key.toString());
}
@Override
public final boolean containsProperty(String key) {
return getApplicationPropertiesMap(false).containsKey(key);
}
@Override
public final Boolean getBooleanProperty(String key) throws ActiveMQPropertyConversionException {
return (Boolean) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Byte getByteProperty(String key) throws ActiveMQPropertyConversionException {
return (Byte) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Double getDoubleProperty(String key) throws ActiveMQPropertyConversionException {
return (Double) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Integer getIntProperty(String key) throws ActiveMQPropertyConversionException {
return (Integer) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Long getLongProperty(String key) throws ActiveMQPropertyConversionException {
return (Long) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Object getObjectProperty(String key) {
switch (key) {
case MessageUtil.TYPE_HEADER_NAME_STRING:
if (properties != null) {
return properties.getSubject();
}
return null;
case MessageUtil.CONNECTION_ID_PROPERTY_NAME_STRING:
return getConnectionID();
case MessageUtil.JMSXGROUPID:
return getGroupID();
case MessageUtil.JMSXGROUPSEQ:
return getGroupSequence();
case MessageUtil.JMSXUSERID:
return getAMQPUserID();
case MessageUtil.CORRELATIONID_HEADER_NAME_STRING:
if (properties != null && properties.getCorrelationId() != null) {
return AMQPMessageIdHelper.INSTANCE.toCorrelationIdString(properties.getCorrelationId());
}
return null;
default:
return getApplicationObjectProperty(key);
}
}
private Object getApplicationObjectProperty(String key) {
Object value = getApplicationPropertiesMap(false).get(key);
if (value instanceof Number) {
// slow path
if (value instanceof UnsignedInteger ||
value instanceof UnsignedByte ||
value instanceof UnsignedLong ||
value instanceof UnsignedShort) {
return ((Number) value).longValue();
}
}
return value;
}
@Override
public final Short getShortProperty(String key) throws ActiveMQPropertyConversionException {
return (Short) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Float getFloatProperty(String key) throws ActiveMQPropertyConversionException {
return (Float) getApplicationPropertiesMap(false).get(key);
}
@Override
public final String getStringProperty(String key) throws ActiveMQPropertyConversionException {
switch (key) {
case MessageUtil.TYPE_HEADER_NAME_STRING:
return properties.getSubject();
case MessageUtil.CONNECTION_ID_PROPERTY_NAME_STRING:
return getConnectionID();
default:
return (String) getApplicationPropertiesMap(false).get(key);
}
}
@Override
public final Set<SimpleString> getPropertyNames() {
HashSet<SimpleString> values = new HashSet<>();
for (Object k : getApplicationPropertiesMap(false).keySet()) {
values.add(SimpleString.toSimpleString(k.toString(), getPropertyKeysPool()));
}
return values;
}
@Override
public final Boolean getBooleanProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getBooleanProperty(key.toString());
}
@Override
public final Byte getByteProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getByteProperty(key.toString());
}
@Override
public final byte[] getBytesProperty(String key) throws ActiveMQPropertyConversionException {
return (byte[]) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Double getDoubleProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getDoubleProperty(key.toString());
}
@Override
public final Integer getIntProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getIntProperty(key.toString());
}
@Override
public final Long getLongProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getLongProperty(key.toString());
}
@Override
public final Object getObjectProperty(SimpleString key) {
return getObjectProperty(key.toString());
}
@Override
public final Short getShortProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getShortProperty(key.toString());
}
@Override
public final Float getFloatProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getFloatProperty(key.toString());
}
@Override
public final String getStringProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getStringProperty(key.toString());
}
@Override
public final SimpleString getSimpleStringProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getSimpleStringProperty(key.toString());
}
@Override
public final byte[] getBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getBytesProperty(key.toString());
}
@Override
public final SimpleString getSimpleStringProperty(String key) throws ActiveMQPropertyConversionException {
return SimpleString.toSimpleString((String) getApplicationPropertiesMap(false).get(key), getPropertyValuesPool());
}
// Core Message Application Property update methods, calling these puts the message in a dirty
// state and requires a re-encode of the data to update all buffer state data. If no re-encode
// is done prior to the next dispatch the old view of the message will be sent.
@Override
public final org.apache.activemq.artemis.api.core.Message putBooleanProperty(String key, boolean value) {
getApplicationPropertiesMap(true).put(key, Boolean.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putByteProperty(String key, byte value) {
getApplicationPropertiesMap(true).put(key, Byte.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putBytesProperty(String key, byte[] value) {
getApplicationPropertiesMap(true).put(key, value);
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putShortProperty(String key, short value) {
getApplicationPropertiesMap(true).put(key, Short.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putCharProperty(String key, char value) {
getApplicationPropertiesMap(true).put(key, Character.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putIntProperty(String key, int value) {
getApplicationPropertiesMap(true).put(key, Integer.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putLongProperty(String key, long value) {
getApplicationPropertiesMap(true).put(key, Long.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putFloatProperty(String key, float value) {
getApplicationPropertiesMap(true).put(key, Float.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putDoubleProperty(String key, double value) {
getApplicationPropertiesMap(true).put(key, Double.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putBooleanProperty(SimpleString key, boolean value) {
getApplicationPropertiesMap(true).put(key.toString(), Boolean.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putByteProperty(SimpleString key, byte value) {
return putByteProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putBytesProperty(SimpleString key, byte[] value) {
return putBytesProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putShortProperty(SimpleString key, short value) {
return putShortProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putCharProperty(SimpleString key, char value) {
return putCharProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putIntProperty(SimpleString key, int value) {
return putIntProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putLongProperty(SimpleString key, long value) {
return putLongProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putFloatProperty(SimpleString key, float value) {
return putFloatProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putDoubleProperty(SimpleString key, double value) {
return putDoubleProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putStringProperty(String key, String value) {
getApplicationPropertiesMap(true).put(key, value);
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putObjectProperty(String key, Object value) throws ActiveMQPropertyConversionException {
getApplicationPropertiesMap(true).put(key, value);
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putObjectProperty(SimpleString key, Object value) throws ActiveMQPropertyConversionException {
return putObjectProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putStringProperty(SimpleString key, SimpleString value) {
return putStringProperty(key.toString(), value.toString());
}
@Override
public final org.apache.activemq.artemis.api.core.Message putStringProperty(SimpleString key, String value) {
return putStringProperty(key.toString(), value);
}
@Override
public final SimpleString getLastValueProperty() {
return getSimpleStringProperty(HDR_LAST_VALUE_NAME);
}
@Override
public final org.apache.activemq.artemis.api.core.Message setLastValueProperty(SimpleString lastValueName) {
return putStringProperty(HDR_LAST_VALUE_NAME, lastValueName);
}
@Override
public String toString() {
MessageDataScanningStatus scanningStatus = getDataScanningStatus();
Map<String, Object> applicationProperties = scanningStatus == MessageDataScanningStatus.SCANNED ?
getApplicationPropertiesMap(false) : Collections.EMPTY_MAP;
return this.getClass().getSimpleName() + "( [durable=" + isDurable() +
", messageID=" + getMessageID() +
", address=" + getAddress() +
", size=" + getEncodeSize() +
", scanningStatus=" + scanningStatus +
", applicationProperties=" + applicationProperties +
", messageAnnotations=" + getMessageAnnotationsMap(false) +
", properties=" + properties +
", extraProperties = " + getExtraProperties() +
"]";
}
@Override
public final synchronized boolean acceptsConsumer(long consumer) {
if (rejectedConsumers == null) {
return true;
} else {
return !rejectedConsumers.contains(consumer);
}
}
@Override
public final synchronized void rejectConsumer(long consumer) {
if (rejectedConsumers == null) {
rejectedConsumers = new HashSet<>();
}
rejectedConsumers.add(consumer);
}
protected SimpleString.StringSimpleStringPool getPropertyKeysPool() {
return coreMessageObjectPools == null ? null : coreMessageObjectPools.getPropertiesStringSimpleStringPools().getPropertyKeysPool();
}
protected SimpleString.StringSimpleStringPool getPropertyValuesPool() {
return coreMessageObjectPools == null ? null : coreMessageObjectPools.getPropertiesStringSimpleStringPools().getPropertyValuesPool();
}
@Override
public Object getOwner() {
return owner;
}
@Override
public void setOwner(Object object) {
this.owner = object;
}
// *******************************************************************************************************************************
// Composite Data implementation
private static MessageOpenTypeFactory AMQP_FACTORY = new AmqpMessageOpenTypeFactory();
static class AmqpMessageOpenTypeFactory extends MessageOpenTypeFactory<AMQPMessage> {
@Override
protected void init() throws OpenDataException {
super.init();
addItem(CompositeDataConstants.TEXT_BODY, CompositeDataConstants.TEXT_BODY, SimpleType.STRING);
}
@Override
public Map<String, Object> getFields(AMQPMessage m, int valueSizeLimit, int delivery) throws OpenDataException {
if (!m.isLargeMessage()) {
m.ensureScanning();
}
Map<String, Object> rc = super.getFields(m, valueSizeLimit, delivery);
Properties properties = m.getCurrentProperties();
byte type = getType(m, properties);
rc.put(CompositeDataConstants.TYPE, type);
if (m.isLargeMessage()) {
rc.put(CompositeDataConstants.TEXT_BODY, "... Large message ...");
} else {
Object amqpValue;
if (m.getBody() instanceof AmqpValue && (amqpValue = ((AmqpValue) m.getBody()).getValue()) != null) {
rc.put(CompositeDataConstants.TEXT_BODY, JsonUtil.truncateString(String.valueOf(amqpValue), valueSizeLimit));
} else {
rc.put(CompositeDataConstants.TEXT_BODY, JsonUtil.truncateString(String.valueOf(m.getBody()), valueSizeLimit));
}
}
return rc;
}
@Override
protected Map<String, Object> expandProperties(AMQPMessage m, int valueSizeLimit) {
return m.toPropertyMap(true, valueSizeLimit);
}
private byte getType(AMQPMessage m, Properties properties) {
if (m.isLargeMessage()) {
return DEFAULT_TYPE;
}
byte type = BYTES_TYPE;
if (m.getBody() == null) {
return DEFAULT_TYPE;
}
final Symbol contentType = properties != null ? properties.getContentType() : null;
if (m.getBody() instanceof Data && contentType != null) {
if (AMQPMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE.equals(contentType)) {
type = OBJECT_TYPE;
} else if (AMQPMessageSupport.OCTET_STREAM_CONTENT_TYPE_SYMBOL.equals(contentType)) {
type = BYTES_TYPE;
} else {
Charset charset = getCharsetForTextualContent(contentType.toString());
if (StandardCharsets.UTF_8.equals(charset)) {
type = TEXT_TYPE;
}
}
} else if (m.getBody() instanceof AmqpValue) {
Object value = ((AmqpValue) m.getBody()).getValue();
if (value instanceof String) {
type = TEXT_TYPE;
} else if (value instanceof Binary) {
if (AMQPMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE.equals(contentType)) {
type = OBJECT_TYPE;
} else {
type = BYTES_TYPE;
}
} else if (value instanceof List) {
type = STREAM_TYPE;
} else if (value instanceof Map) {
type = MAP_TYPE;
}
} else if (m.getBody() instanceof AmqpSequence) {
type = STREAM_TYPE;
}
return type;
}
}
@Override
public CompositeData toCompositeData(int fieldsLimit, int deliveryCount) throws OpenDataException {
Map<String, Object> fields;
fields = AMQP_FACTORY.getFields(this, fieldsLimit, deliveryCount);
return new CompositeDataSupport(AMQP_FACTORY.getCompositeType(), fields);
}
// Composite Data implementation
// *******************************************************************************************************************************
} | artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPMessage.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.activemq.artemis.protocol.amqp.broker;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.SimpleType;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQPropertyConversionException;
import org.apache.activemq.artemis.api.core.ICoreMessage;
import org.apache.activemq.artemis.api.core.JsonUtil;
import org.apache.activemq.artemis.api.core.RefCountMessage;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.message.openmbean.CompositeDataConstants;
import org.apache.activemq.artemis.core.message.openmbean.MessageOpenTypeFactory;
import org.apache.activemq.artemis.core.paging.PagingStore;
import org.apache.activemq.artemis.core.persistence.CoreMessageObjectPools;
import org.apache.activemq.artemis.core.persistence.Persister;
import org.apache.activemq.artemis.core.server.MessageReference;
import org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageIdHelper;
import org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport;
import org.apache.activemq.artemis.protocol.amqp.converter.AmqpCoreConverter;
import org.apache.activemq.artemis.protocol.amqp.util.NettyReadable;
import org.apache.activemq.artemis.protocol.amqp.util.NettyWritable;
import org.apache.activemq.artemis.protocol.amqp.util.TLSEncode;
import org.apache.activemq.artemis.reader.MessageUtil;
import org.apache.activemq.artemis.utils.ByteUtil;
import org.apache.activemq.artemis.utils.collections.TypedProperties;
import org.apache.qpid.proton.amqp.Binary;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.UnsignedByte;
import org.apache.qpid.proton.amqp.UnsignedInteger;
import org.apache.qpid.proton.amqp.UnsignedLong;
import org.apache.qpid.proton.amqp.UnsignedShort;
import org.apache.qpid.proton.amqp.messaging.AmqpSequence;
import org.apache.qpid.proton.amqp.messaging.AmqpValue;
import org.apache.qpid.proton.amqp.messaging.ApplicationProperties;
import org.apache.qpid.proton.amqp.messaging.Data;
import org.apache.qpid.proton.amqp.messaging.DeliveryAnnotations;
import org.apache.qpid.proton.amqp.messaging.Footer;
import org.apache.qpid.proton.amqp.messaging.Header;
import org.apache.qpid.proton.amqp.messaging.MessageAnnotations;
import org.apache.qpid.proton.amqp.messaging.Properties;
import org.apache.qpid.proton.amqp.messaging.Section;
import org.apache.qpid.proton.codec.DecoderImpl;
import org.apache.qpid.proton.codec.DroppingWritableBuffer;
import org.apache.qpid.proton.codec.ReadableBuffer;
import org.apache.qpid.proton.codec.TypeConstructor;
import org.apache.qpid.proton.codec.WritableBuffer;
import org.apache.qpid.proton.message.Message;
import org.apache.qpid.proton.message.impl.MessageImpl;
import org.jboss.logging.Logger;
import static org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport.getCharsetForTextualContent;
/**
* See <a href="https://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#section-message-format">AMQP v1.0 message format</a>
* <pre>
*
* Bare Message
* |
* .---------------------+--------------------.
* | |
* +--------+-------------+-------------+------------+--------------+--------------+--------+
* | header | delivery- | message- | properties | application- | application- | footer |
* | | annotations | annotations | | properties | data | |
* +--------+-------------+-------------+------------+--------------+--------------+--------+
* | |
* '-------------------------------------------+--------------------------------------------'
* |
* Annotated Message
* </pre>
* <ul>
* <li>Zero or one header sections.
* <li>Zero or one delivery-annotation sections.
* <li>Zero or one message-annotation sections.
* <li>Zero or one properties sections.
* <li>Zero or one application-properties sections.
* <li>The body consists of one of the following three choices:
* <ul>
* <li>one or more data sections
* <li>one or more amqp-sequence sections
* <li>or a single amqp-value section.
* </ul>
* <li>Zero or one footer sections.
* </ul>
*/
public abstract class AMQPMessage extends RefCountMessage implements org.apache.activemq.artemis.api.core.Message {
private static final SimpleString ANNOTATION_AREA_PREFIX = SimpleString.toSimpleString("m.");
protected static final Logger logger = Logger.getLogger(AMQPMessage.class);
public static final SimpleString ADDRESS_PROPERTY = SimpleString.toSimpleString("_AMQ_AD");
// used to perform quick search
private static final Symbol[] SCHEDULED_DELIVERY_SYMBOLS = new Symbol[]{
AMQPMessageSupport.SCHEDULED_DELIVERY_TIME, AMQPMessageSupport.SCHEDULED_DELIVERY_DELAY};
private static final KMPNeedle[] SCHEDULED_DELIVERY_NEEDLES = new KMPNeedle[]{
AMQPMessageSymbolSearch.kmpNeedleOf(AMQPMessageSupport.SCHEDULED_DELIVERY_TIME),
AMQPMessageSymbolSearch.kmpNeedleOf(AMQPMessageSupport.SCHEDULED_DELIVERY_DELAY)};
private static final KMPNeedle[] DUPLICATE_ID_NEEDLES = new KMPNeedle[] {
AMQPMessageSymbolSearch.kmpNeedleOf(org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString())
};
public static final int DEFAULT_MESSAGE_FORMAT = 0;
public static final int DEFAULT_MESSAGE_PRIORITY = 4;
public static final int MAX_MESSAGE_PRIORITY = 9;
protected static final int VALUE_NOT_PRESENT = -1;
/**
* This has been made public just for testing purposes: it's not stable
* and developers shouldn't rely on this for developing purposes.
*/
public enum MessageDataScanningStatus {
NOT_SCANNED(0), RELOAD_PERSISTENCE(1), SCANNED(2);
private static final MessageDataScanningStatus[] STATES;
static {
// this prevent codes to be assigned with the wrong order
// and ensure valueOf to work fine
final MessageDataScanningStatus[] states = values();
STATES = new MessageDataScanningStatus[states.length];
for (final MessageDataScanningStatus state : states) {
final int code = state.code;
if (STATES[code] != null) {
throw new AssertionError("code already in use: " + code);
}
STATES[code] = state;
}
}
final byte code;
MessageDataScanningStatus(int code) {
assert code >= 0 && code <= Byte.MAX_VALUE;
this.code = (byte) code;
}
static MessageDataScanningStatus valueOf(int code) {
checkCode(code);
return STATES[code];
}
private static void checkCode(int code) {
if (code < 0 || code > (STATES.length - 1)) {
throw new IllegalArgumentException("invalid status code: " + code);
}
}
}
// Buffer and state for the data backing this message.
protected byte messageDataScanned = MessageDataScanningStatus.NOT_SCANNED.code;
// Marks the message as needed to be re-encoded to update the backing buffer
protected boolean modified;
// Track locations of the message sections for later use and track the size
// of the header and delivery annotations if present so we can easily exclude
// the delivery annotations later and perform efficient encodes or copies.
protected int headerPosition = VALUE_NOT_PRESENT;
protected int encodedHeaderSize;
protected int deliveryAnnotationsPosition = VALUE_NOT_PRESENT;
protected int encodedDeliveryAnnotationsSize;
protected int messageAnnotationsPosition = VALUE_NOT_PRESENT;
protected int propertiesPosition = VALUE_NOT_PRESENT;
protected int applicationPropertiesPosition = VALUE_NOT_PRESENT;
protected int remainingBodyPosition = VALUE_NOT_PRESENT;
// Message level meta data
protected final long messageFormat;
protected long messageID;
protected SimpleString address;
protected volatile int memoryEstimate = -1;
protected long expiration;
protected boolean expirationReload = false;
protected long scheduledTime = -1;
// The Proton based AMQP message section that are retained in memory, these are the
// mutable portions of the Message as the broker sees it, although AMQP defines that
// the Properties and ApplicationProperties are immutable so care should be taken
// here when making changes to those Sections.
protected Header header;
protected MessageAnnotations messageAnnotations;
protected Properties properties;
protected ApplicationProperties applicationProperties;
protected String connectionID;
protected final CoreMessageObjectPools coreMessageObjectPools;
protected Set<Object> rejectedConsumers;
protected DeliveryAnnotations deliveryAnnotationsForSendBuffer;
protected DeliveryAnnotations deliveryAnnotations;
// These are properties set at the broker level and carried only internally by broker storage.
protected volatile TypedProperties extraProperties;
private volatile Object owner;
/**
* Creates a new {@link AMQPMessage} instance from binary encoded message data.
*
* @param messageFormat
* The Message format tag given the in Transfer that carried this message
* @param extraProperties
* Broker specific extra properties that should be carried with this message
*/
public AMQPMessage(long messageFormat, TypedProperties extraProperties, CoreMessageObjectPools coreMessageObjectPools) {
this.messageFormat = messageFormat;
this.coreMessageObjectPools = coreMessageObjectPools;
this.extraProperties = extraProperties == null ? null : new TypedProperties(extraProperties);
}
protected AMQPMessage(AMQPMessage copy) {
this(copy.messageFormat, copy.extraProperties, copy.coreMessageObjectPools);
this.headerPosition = copy.headerPosition;
this.encodedHeaderSize = copy.encodedHeaderSize;
this.header = copy.header == null ? null : new Header(copy.header);
this.deliveryAnnotationsPosition = copy.deliveryAnnotationsPosition;
this.encodedDeliveryAnnotationsSize = copy.encodedDeliveryAnnotationsSize;
this.deliveryAnnotations = copy.deliveryAnnotations == null ? null : new DeliveryAnnotations(copy.deliveryAnnotations.getValue());
this.messageAnnotationsPosition = copy.messageAnnotationsPosition;
this.messageAnnotations = copy.messageAnnotations == null ? null : new MessageAnnotations(copy.messageAnnotations.getValue());
this.propertiesPosition = copy.propertiesPosition;
this.properties = copy.properties == null ? null : new Properties(copy.properties);
this.applicationPropertiesPosition = copy.applicationPropertiesPosition;
this.applicationProperties = copy.applicationProperties == null ? null : new ApplicationProperties(copy.applicationProperties.getValue());
this.remainingBodyPosition = copy.remainingBodyPosition;
this.messageDataScanned = copy.messageDataScanned;
}
protected AMQPMessage(long messageFormat) {
this.messageFormat = messageFormat;
this.coreMessageObjectPools = null;
}
@Override
public String getProtocolName() {
return ProtonProtocolManagerFactory.AMQP_PROTOCOL_NAME;
}
public final MessageDataScanningStatus getDataScanningStatus() {
return MessageDataScanningStatus.valueOf(messageDataScanned);
}
/** This will return application properties without attempting to decode it.
* That means, if applicationProperties were never parsed before, this will return null, even if there is application properties.
* This was created as an internal method for testing, as we need to validate if the application properties are not decoded until needed. */
protected ApplicationProperties getDecodedApplicationProperties() {
return applicationProperties;
}
protected MessageAnnotations getDecodedMessageAnnotations() {
return messageAnnotations;
}
protected abstract ReadableBuffer getData();
// Access to the AMQP message data using safe copies freshly decoded from the current
// AMQP message data stored in this message wrapper. Changes to these values cannot
// be used to influence the underlying AMQP message data, the standard AMQPMessage API
// must be used to make changes to mutable portions of the message.
/**
* Creates and returns a Proton-J MessageImpl wrapper around the message data. Changes to
* the returned Message are not reflected in this message.
*
* @return a MessageImpl that wraps the AMQP message data in this {@link AMQPMessage}
*/
public final MessageImpl getProtonMessage() {
if (getData() == null) {
throw new NullPointerException("Data is not initialized");
}
ensureScanning();
MessageImpl protonMessage = null;
if (getData() != null) {
protonMessage = (MessageImpl) Message.Factory.create();
getData().rewind();
protonMessage.decode(getData().duplicate());
}
return protonMessage;
}
@Override
public Object getObjectPropertyForFilter(SimpleString key) {
if (key.startsWith(ANNOTATION_AREA_PREFIX)) {
key = key.subSeq(ANNOTATION_AREA_PREFIX.length(), key.length());
return getAnnotation(key);
}
Object value = getObjectProperty(key);
if (value == null) {
TypedProperties extra = getExtraProperties();
if (extra != null) {
value = extra.getProperty(key);
}
}
return value;
}
/**
* Returns a copy of the message Header if one is present, changes to the returned
* Header instance do not affect the original Message.
*
* @return a copy of the Message Header if one exists or null if none present.
*/
public final Header getHeader() {
ensureScanning();
return scanForMessageSection(headerPosition, Header.class);
}
/** Returns the current already scanned header. */
final Header getCurrentHeader() {
return header;
}
/** Return the current already scanned properties.*/
final Properties getCurrentProperties() {
return properties;
}
protected void ensureScanning() {
ensureDataIsValid();
ensureMessageDataScanned();
}
Object getDeliveryAnnotationProperty(Symbol symbol) {
DeliveryAnnotations daToUse = deliveryAnnotations;
if (daToUse == null) {
daToUse = getDeliveryAnnotations();
}
if (daToUse == null) {
return null;
} else {
return daToUse.getValue().get(symbol);
}
}
/**
* Returns a copy of the MessageAnnotations in the message if present or null. Changes to the
* returned DeliveryAnnotations instance do not affect the original Message.
*
* @return a copy of the {@link DeliveryAnnotations} present in the message or null if non present.
*/
public final DeliveryAnnotations getDeliveryAnnotations() {
ensureScanning();
return scanForMessageSection(deliveryAnnotationsPosition, DeliveryAnnotations.class);
}
/**
* Sets the delivery annotations to be included when encoding the message for sending it on the wire.
*
* The broker can add additional message annotations as long as the annotations being added follow the
* rules from the spec. If the user adds something that the remote doesn't understand and it is not
* prefixed with "x-opt" the remote can just kill the link. See:
*
* http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-annotations
*
* @deprecated use MessageReference.setProtocolData(deliveryAnnotations)
* @param deliveryAnnotations delivery annotations used in the sendBuffer() method
*/
@Deprecated
public final void setDeliveryAnnotationsForSendBuffer(DeliveryAnnotations deliveryAnnotations) {
this.deliveryAnnotationsForSendBuffer = deliveryAnnotations;
}
/**
* Returns a copy of the DeliveryAnnotations in the message if present or null. Changes to the
* returned MessageAnnotations instance do not affect the original Message.
*
* @return a copy of the {@link MessageAnnotations} present in the message or null if non present.
*/
public final MessageAnnotations getMessageAnnotations() {
ensureScanning();
return scanForMessageSection(messageAnnotationsPosition, MessageAnnotations.class);
}
/**
* Returns a copy of the message Properties if one is present, changes to the returned
* Properties instance do not affect the original Message.
*
* @return a copy of the Message Properties if one exists or null if none present.
*/
public final Properties getProperties() {
ensureScanning();
return scanForMessageSection(propertiesPosition, Properties.class);
}
/**
* Returns a copy of the {@link ApplicationProperties} present in the message if present or null.
* Changes to the returned MessageAnnotations instance do not affect the original Message.
*
* @return a copy of the {@link ApplicationProperties} present in the message or null if non present.
*/
public final ApplicationProperties getApplicationProperties() {
ensureScanning();
return scanForMessageSection(applicationPropertiesPosition, ApplicationProperties.class);
}
/** This is different from toString, as this will print an expanded version of the buffer
* in Hex and programmers's readable format */
public final String toDebugString() {
return ByteUtil.debugByteArray(getData().array());
}
/**
* Retrieves the AMQP Section that composes the body of this message by decoding a
* fresh copy from the encoded message data. Changes to the returned value are not
* reflected in the value encoded in the original message.
*
* @return the Section that makes up the body of this message.
*/
public final Section getBody() {
ensureScanning();
// We only handle Sections of AmqpSequence, AmqpValue and Data types so we filter on those.
// There could also be a Footer and no body so this will prevent a faulty return type in case
// of no body or message type we don't handle.
return scanForMessageSection(Math.max(0, remainingBodyPosition), AmqpSequence.class, AmqpValue.class, Data.class);
}
/**
* Retrieves the AMQP Footer encoded in the data of this message by decoding a
* fresh copy from the encoded message data. Changes to the returned value are not
* reflected in the value encoded in the original message.
*
* @return the Footer that was encoded into this AMQP Message.
*/
public final Footer getFooter() {
ensureScanning();
return scanForMessageSection(Math.max(0, remainingBodyPosition), Footer.class);
}
protected <T> T scanForMessageSection(int scanStartPosition, Class...targetTypes) {
return scanForMessageSection(getData().duplicate().position(0), scanStartPosition, targetTypes);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected <T> T scanForMessageSection(ReadableBuffer buffer, int scanStartPosition, Class...targetTypes) {
ensureMessageDataScanned();
// In cases where we parsed out enough to know the value is not encoded in the message
// we can exit without doing any reads or buffer hopping.
if (scanStartPosition == VALUE_NOT_PRESENT) {
return null;
}
final DecoderImpl decoder = TLSEncode.getDecoder();
buffer.position(scanStartPosition);
T section = null;
decoder.setBuffer(buffer);
try {
while (buffer.hasRemaining()) {
TypeConstructor<?> constructor = decoder.readConstructor();
for (Class<?> type : targetTypes) {
if (type.equals(constructor.getTypeClass())) {
section = (T) constructor.readValue();
return section;
}
}
constructor.skipValue();
}
} finally {
decoder.setBuffer(null);
}
return section;
}
protected ApplicationProperties lazyDecodeApplicationProperties() {
ensureMessageDataScanned();
if (applicationProperties != null || applicationPropertiesPosition == VALUE_NOT_PRESENT) {
return applicationProperties;
}
return lazyDecodeApplicationProperties(getData().duplicate().position(0));
}
protected ApplicationProperties lazyDecodeApplicationProperties(ReadableBuffer data) {
if (applicationProperties == null && applicationPropertiesPosition != VALUE_NOT_PRESENT) {
applicationProperties = scanForMessageSection(data, applicationPropertiesPosition, ApplicationProperties.class);
if (owner != null && memoryEstimate != -1) {
// the memory has already been tracked and needs to be updated to reflect the new decoding
int addition = unmarshalledApplicationPropertiesMemoryEstimateFromData(data);
((PagingStore)owner).addSize(addition, false);
final int updatedEstimate = memoryEstimate + addition;
memoryEstimate = updatedEstimate;
}
}
return applicationProperties;
}
protected int unmarshalledApplicationPropertiesMemoryEstimateFromData(ReadableBuffer data) {
if (applicationProperties != null) {
// they have been unmarshalled, estimate memory usage based on their encoded size
if (remainingBodyPosition != VALUE_NOT_PRESENT) {
return remainingBodyPosition - applicationPropertiesPosition;
} else {
return data.capacity() - applicationPropertiesPosition;
}
}
return 0;
}
@SuppressWarnings("unchecked")
protected Map<String, Object> getApplicationPropertiesMap(boolean createIfAbsent) {
ApplicationProperties appMap = lazyDecodeApplicationProperties();
Map<String, Object> map = null;
if (appMap != null) {
map = appMap.getValue();
}
if (map == null) {
if (createIfAbsent) {
map = new HashMap<>();
this.applicationProperties = new ApplicationProperties(map);
} else {
map = Collections.EMPTY_MAP;
}
}
return map;
}
@SuppressWarnings("unchecked")
protected Map<Symbol, Object> getMessageAnnotationsMap(boolean createIfAbsent) {
Map<Symbol, Object> map = null;
if (messageAnnotations != null) {
map = messageAnnotations.getValue();
}
if (map == null) {
if (createIfAbsent) {
map = new HashMap<>();
this.messageAnnotations = new MessageAnnotations(map);
} else {
map = Collections.EMPTY_MAP;
}
}
return map;
}
protected Object getMessageAnnotation(String annotation) {
Object messageAnnotation = getMessageAnnotation(Symbol.getSymbol(AMQPMessageSupport.toAnnotationName(annotation)));
if (messageAnnotation == null) {
messageAnnotation = getMessageAnnotation(Symbol.getSymbol(annotation));
}
return messageAnnotation;
}
protected Object getMessageAnnotation(Symbol annotation) {
return getMessageAnnotationsMap(false).get(annotation);
}
protected Object removeMessageAnnotation(Symbol annotation) {
return getMessageAnnotationsMap(false).remove(annotation);
}
protected void setMessageAnnotation(String annotation, Object value) {
setMessageAnnotation(Symbol.getSymbol(annotation), value);
}
protected void setMessageAnnotation(Symbol annotation, Object value) {
if (value instanceof SimpleString) {
value = value.toString();
}
getMessageAnnotationsMap(true).put(annotation, value);
}
protected void setMessageAnnotations(MessageAnnotations messageAnnotations) {
this.messageAnnotations = messageAnnotations;
}
// Message decoding and copying methods. Care must be taken here to ensure the buffer and the
// state tracking information is kept up to data. When the message is manually changed a forced
// re-encode should be done to update the backing data with the in memory elements.
protected synchronized void ensureMessageDataScanned() {
final MessageDataScanningStatus state = getDataScanningStatus();
switch (state) {
case NOT_SCANNED:
scanMessageData();
break;
case RELOAD_PERSISTENCE:
lazyScanAfterReloadPersistence();
break;
case SCANNED:
// NO-OP
break;
}
}
protected int getEstimateSavedEncode() {
return remainingBodyPosition > 0 ? remainingBodyPosition : 1024;
}
protected synchronized void resetMessageData() {
header = null;
messageAnnotations = null;
properties = null;
applicationProperties = null;
if (!expirationReload) {
expiration = 0;
}
encodedHeaderSize = 0;
memoryEstimate = -1;
scheduledTime = -1;
encodedDeliveryAnnotationsSize = 0;
headerPosition = VALUE_NOT_PRESENT;
deliveryAnnotationsPosition = VALUE_NOT_PRESENT;
propertiesPosition = VALUE_NOT_PRESENT;
applicationPropertiesPosition = VALUE_NOT_PRESENT;
remainingBodyPosition = VALUE_NOT_PRESENT;
}
protected synchronized void scanMessageData() {
scanMessageData(getData());
}
protected synchronized void scanMessageData(ReadableBuffer data) {
DecoderImpl decoder = TLSEncode.getDecoder();
decoder.setBuffer(data);
resetMessageData();
try {
while (data.hasRemaining()) {
int constructorPos = data.position();
TypeConstructor<?> constructor = decoder.readConstructor();
if (Header.class.equals(constructor.getTypeClass())) {
header = (Header) constructor.readValue();
headerPosition = constructorPos;
encodedHeaderSize = data.position();
if (header.getTtl() != null) {
if (!expirationReload) {
expiration = System.currentTimeMillis() + header.getTtl().intValue();
}
}
} else if (DeliveryAnnotations.class.equals(constructor.getTypeClass())) {
deliveryAnnotationsPosition = constructorPos;
this.deliveryAnnotations = (DeliveryAnnotations) constructor.readValue();
encodedDeliveryAnnotationsSize = data.position() - constructorPos;
} else if (MessageAnnotations.class.equals(constructor.getTypeClass())) {
messageAnnotationsPosition = constructorPos;
messageAnnotations = (MessageAnnotations) constructor.readValue();
} else if (Properties.class.equals(constructor.getTypeClass())) {
propertiesPosition = constructorPos;
properties = (Properties) constructor.readValue();
if (properties.getAbsoluteExpiryTime() != null && properties.getAbsoluteExpiryTime().getTime() > 0) {
if (!expirationReload) {
expiration = properties.getAbsoluteExpiryTime().getTime();
}
}
} else if (ApplicationProperties.class.equals(constructor.getTypeClass())) {
// Lazy decoding will start at the TypeConstructor of these ApplicationProperties
// but we scan past it to grab the location of the possible body and footer section.
applicationPropertiesPosition = constructorPos;
constructor.skipValue();
remainingBodyPosition = data.hasRemaining() ? data.position() : VALUE_NOT_PRESENT;
break;
} else {
// This will be either the body or a Footer section which will be treated as an immutable
// and be copied as is when re-encoding the message.
remainingBodyPosition = constructorPos;
break;
}
}
} finally {
decoder.setBuffer(null);
data.rewind();
}
this.messageDataScanned = MessageDataScanningStatus.SCANNED.code;
}
@Override
public abstract org.apache.activemq.artemis.api.core.Message copy();
// Core Message APIs for persisting and encoding of message data along with
// utilities for checking memory usage and encoded size characteristics.
/**
* Would be called by the Artemis Core components to encode the message into
* the provided send buffer. Because of how Proton message data handling works
* this method is not currently used by the AMQP protocol head and will not be
* called for out-bound sends.
*
* @see #getSendBuffer(int, MessageReference) for the actual method used for message sends.
*/
@Override
public final void sendBuffer(ByteBuf buffer, int deliveryCount) {
ensureDataIsValid();
NettyWritable writable = new NettyWritable(buffer);
writable.put(getSendBuffer(deliveryCount, null));
}
/**
* Gets a ByteBuf from the Message that contains the encoded bytes to be sent on the wire.
* <p>
* When possible this method will present the bytes to the caller without copying them into
* a new buffer copy. If copying is needed a new Netty buffer is created and returned. The
* caller should ensure that the reference count on the returned buffer is always decremented
* to avoid a leak in the case of a copied buffer being returned.
*
* @param deliveryCount
* The new delivery count for this message.
*
* @return a Netty ByteBuf containing the encoded bytes of this Message instance.
*/
public ReadableBuffer getSendBuffer(int deliveryCount, MessageReference reference) {
ensureDataIsValid();
DeliveryAnnotations daToWrite;
if (reference != null && reference.getProtocolData() instanceof DeliveryAnnotations) {
daToWrite = (DeliveryAnnotations) reference.getProtocolData();
} else {
// deliveryAnnotationsForSendBuffer was an old API form where a deliver could set it before deliver
daToWrite = deliveryAnnotationsForSendBuffer;
}
if (deliveryCount > 1 || daToWrite != null || deliveryAnnotationsPosition != VALUE_NOT_PRESENT) {
return createDeliveryCopy(deliveryCount, daToWrite);
} else {
// Common case message has no delivery annotations, no delivery annotations for the send buffer were set
// and this is the first delivery so no re-encoding or section skipping needed.
return getData().duplicate();
}
}
/** it will create a copy with the relevant delivery annotation and its copy */
protected ReadableBuffer createDeliveryCopy(int deliveryCount, DeliveryAnnotations deliveryAnnotations) {
ReadableBuffer duplicate = getData().duplicate();
final int amqpDeliveryCount = deliveryCount - 1;
final ByteBuf result = PooledByteBufAllocator.DEFAULT.heapBuffer(getEncodeSize());
// If this is re-delivering the message then the header must be re-encoded
// otherwise we want to write the original header if present. When a
// Header is present we need to copy it as we are updating the re-delivered
// message and not the stored version which we don't want to invalidate here.
Header localHeader = this.header;
if (localHeader == null) {
if (deliveryCount > 1) {
localHeader = new Header();
}
} else {
localHeader = new Header(header);
}
if (localHeader != null) {
localHeader.setDeliveryCount(UnsignedInteger.valueOf(amqpDeliveryCount));
TLSEncode.getEncoder().setByteBuffer(new NettyWritable(result));
TLSEncode.getEncoder().writeObject(localHeader);
TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null);
}
writeDeliveryAnnotationsForSendBuffer(result, deliveryAnnotations);
// skip existing delivery annotations of the original message
duplicate.position(encodedHeaderSize + encodedDeliveryAnnotationsSize);
result.writeBytes(duplicate.byteBuffer());
return new NettyReadable(result);
}
protected void writeDeliveryAnnotationsForSendBuffer(ByteBuf result, DeliveryAnnotations deliveryAnnotations) {
if (deliveryAnnotations != null && !deliveryAnnotations.getValue().isEmpty()) {
TLSEncode.getEncoder().setByteBuffer(new NettyWritable(result));
TLSEncode.getEncoder().writeObject(deliveryAnnotations);
TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null);
}
}
protected int getDeliveryAnnotationsForSendBufferSize() {
if (deliveryAnnotationsForSendBuffer == null || deliveryAnnotationsForSendBuffer.getValue().isEmpty()) {
return 0;
}
DroppingWritableBuffer droppingWritableBuffer = new DroppingWritableBuffer();
TLSEncode.getEncoder().setByteBuffer(droppingWritableBuffer);
TLSEncode.getEncoder().writeObject(deliveryAnnotationsForSendBuffer);
TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null);
return droppingWritableBuffer.position() + 1;
}
@Override
public void messageChanged() {
modified = true;
}
@Override
public abstract int getEncodeSize();
@Override
public final void receiveBuffer(ByteBuf buffer) {
// Not used for AMQP messages.
}
@Override
public abstract int getMemoryEstimate();
@Override
public Map<String, Object> toPropertyMap(int valueSizeLimit) {
return toPropertyMap(false, valueSizeLimit);
}
private Map<String, Object> toPropertyMap(boolean expandPropertyType, int valueSizeLimit) {
String extraPropertiesPrefix;
String applicationPropertiesPrefix;
String annotationPrefix;
String propertiesPrefix;
if (expandPropertyType) {
extraPropertiesPrefix = "extraProperties.";
applicationPropertiesPrefix = "applicationProperties.";
annotationPrefix = "messageAnnotations.";
propertiesPrefix = "properties.";
} else {
extraPropertiesPrefix = "";
applicationPropertiesPrefix = "";
annotationPrefix = "";
propertiesPrefix = "";
}
Map map = new HashMap<>();
for (SimpleString name : getPropertyNames()) {
Object value = getObjectProperty(name.toString());
//some property is Binary, which is not available for management console
if (value instanceof Binary) {
value = ((Binary)value).getArray();
}
map.put(applicationPropertiesPrefix + name, JsonUtil.truncate(value, valueSizeLimit));
}
TypedProperties extraProperties = getExtraProperties();
if (extraProperties != null) {
extraProperties.forEach((s, o) -> {
if (o instanceof Number) {
// keep fields like _AMQ_ACTUAL_EXPIRY in their original type
map.put(extraPropertiesPrefix + s.toString(), o);
} else {
map.put(extraPropertiesPrefix + s.toString(), JsonUtil.truncate(o != null ? o.toString() : o, valueSizeLimit));
}
});
}
addAnnotationsAsProperties(annotationPrefix, map, messageAnnotations);
if (properties != null) {
if (properties.getContentType() != null) {
map.put(propertiesPrefix + "contentType", properties.getContentType().toString());
}
if (properties.getContentEncoding() != null) {
map.put(propertiesPrefix + "contentEncoding", properties.getContentEncoding().toString());
}
if (properties.getGroupId() != null) {
map.put(propertiesPrefix + "groupId", properties.getGroupId());
}
if (properties.getGroupSequence() != null) {
map.put(propertiesPrefix + "groupSequence", properties.getGroupSequence().intValue());
}
if (properties.getReplyToGroupId() != null) {
map.put(propertiesPrefix + "replyToGroupId", properties.getReplyToGroupId());
}
if (properties.getCreationTime() != null) {
map.put(propertiesPrefix + "creationTime", properties.getCreationTime().getTime());
}
if (properties.getAbsoluteExpiryTime() != null) {
map.put(propertiesPrefix + "absoluteExpiryTime", properties.getAbsoluteExpiryTime().getTime());
}
if (properties.getTo() != null) {
map.put(propertiesPrefix + "to", properties.getTo());
}
if (properties.getSubject() != null) {
map.put(propertiesPrefix + "subject", properties.getSubject());
}
}
return map;
}
protected static void addAnnotationsAsProperties(String prefix, Map map, MessageAnnotations annotations) {
if (annotations != null && annotations.getValue() != null) {
for (Map.Entry<?, ?> entry : annotations.getValue().entrySet()) {
String key = entry.getKey().toString();
if ("x-opt-delivery-time".equals(key) && entry.getValue() != null) {
long deliveryTime = ((Number) entry.getValue()).longValue();
map.put(prefix + "x-opt-delivery-time", deliveryTime);
} else if ("x-opt-delivery-delay".equals(key) && entry.getValue() != null) {
long delay = ((Number) entry.getValue()).longValue();
map.put(prefix + "x-opt-delivery-delay", delay);
} else if (AMQPMessageSupport.X_OPT_INGRESS_TIME.equals(key) && entry.getValue() != null) {
map.put(prefix + AMQPMessageSupport.X_OPT_INGRESS_TIME, ((Number) entry.getValue()).longValue());
} else {
try {
map.put(prefix + key, entry.getValue());
} catch (ActiveMQPropertyConversionException e) {
logger.warn(e.getMessage(), e);
}
}
}
}
}
@Override
public ICoreMessage toCore(CoreMessageObjectPools coreMessageObjectPools) {
try {
ensureScanning();
return AmqpCoreConverter.toCore(
this, coreMessageObjectPools, header, messageAnnotations, properties, lazyDecodeApplicationProperties(), getBody(), getFooter());
} catch (Exception e) {
logger.warn(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
public ICoreMessage toCore() {
return toCore(coreMessageObjectPools);
}
@Override
public abstract void persist(ActiveMQBuffer targetRecord);
@Override
public abstract int getPersistSize();
protected int internalPersistSize() {
return getData().remaining();
}
@Override
public abstract void reloadPersistence(ActiveMQBuffer record, CoreMessageObjectPools pools);
protected synchronized void lazyScanAfterReloadPersistence() {
assert messageDataScanned == MessageDataScanningStatus.RELOAD_PERSISTENCE.code;
scanMessageData();
messageDataScanned = MessageDataScanningStatus.SCANNED.code;
modified = false;
// reinitialise memory estimate as message will already be on a queue
// and lazy decode will want to update
getMemoryEstimate();
}
@Override
public abstract long getPersistentSize() throws ActiveMQException;
@Override
public abstract Persister<org.apache.activemq.artemis.api.core.Message> getPersister();
@Override
public abstract void reencode();
protected abstract void ensureDataIsValid();
protected abstract void encodeMessage();
// These methods interact with the Extra Properties that can accompany the message but
// because these are not sent on the wire, update to these does not force a re-encode on
// send of the message.
public final TypedProperties createExtraProperties() {
if (extraProperties == null) {
extraProperties = new TypedProperties(INTERNAL_PROPERTY_NAMES_PREDICATE);
}
return extraProperties;
}
public final TypedProperties getExtraProperties() {
return extraProperties;
}
public final AMQPMessage setExtraProperties(TypedProperties extraProperties) {
this.extraProperties = extraProperties;
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putExtraBytesProperty(SimpleString key, byte[] value) {
createExtraProperties().putBytesProperty(key, value);
return this;
}
@Override
public final byte[] getExtraBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException {
if (extraProperties == null) {
return null;
} else {
return extraProperties.getBytesProperty(key);
}
}
@Override
public void clearInternalProperties() {
if (extraProperties != null) {
extraProperties.clearInternalProperties();
}
}
@Override
public final byte[] removeExtraBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException {
if (extraProperties == null) {
return null;
} else {
return (byte[])extraProperties.removeProperty(key);
}
}
// Message meta data access for Core and AMQP usage.
@Override
public final org.apache.activemq.artemis.api.core.Message setConnectionID(String connectionID) {
this.connectionID = connectionID;
return this;
}
@Override
public final String getConnectionID() {
return connectionID;
}
public final long getMessageFormat() {
return messageFormat;
}
@Override
public final long getMessageID() {
return messageID;
}
@Override
public final org.apache.activemq.artemis.api.core.Message setMessageID(long id) {
this.messageID = id;
return this;
}
@Override
public final long getExpiration() {
if (!expirationReload) {
ensureMessageDataScanned();
}
return expiration;
}
public void reloadExpiration(long expiration) {
this.expiration = expiration;
this.expirationReload = true;
}
@Override
public final AMQPMessage setExpiration(long expiration) {
if (properties != null) {
if (expiration <= 0) {
properties.setAbsoluteExpiryTime(null);
} else {
properties.setAbsoluteExpiryTime(new Date(expiration));
}
} else if (expiration > 0) {
properties = new Properties();
properties.setAbsoluteExpiryTime(new Date(expiration));
}
// We are overriding expiration with an Absolute expiration time so any
// previous Header based TTL also needs to be removed.
if (header != null) {
header.setTtl(null);
}
this.expiration = Math.max(0, expiration);
return this;
}
@Override
public final Object getUserID() {
// User ID in Artemis API means Message ID
if (properties != null && properties.getMessageId() != null) {
return properties.getMessageId();
} else {
return null;
}
}
/**
* Before we added AMQP into Artemis the name getUserID was already taken by JMSMessageID.
* We cannot simply change the names now as it would break the API for existing clients.
*
* This is to return and read the proper AMQP userID.
*
* @return the UserID value in the AMQP Properties if one is present.
*/
public final Object getAMQPUserID() {
if (properties != null && properties.getUserId() != null) {
Binary binary = properties.getUserId();
return new String(binary.getArray(), binary.getArrayOffset(), binary.getLength(), StandardCharsets.UTF_8);
} else {
return null;
}
}
@Override
public final org.apache.activemq.artemis.api.core.Message setUserID(Object userID) {
return this;
}
@Override
public final Object getDuplicateProperty() {
if (applicationProperties == null && messageDataScanned == MessageDataScanningStatus.SCANNED.code && applicationPropertiesPosition != VALUE_NOT_PRESENT) {
if (!AMQPMessageSymbolSearch.anyApplicationProperties(getData(), DUPLICATE_ID_NEEDLES, applicationPropertiesPosition)) {
// no need for duplicate-property
return null;
}
}
return getApplicationObjectProperty(org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString());
}
@Override
public boolean isDurable() {
if (header != null && header .getDurable() != null) {
return header.getDurable();
} else {
// if header == null and scanningStatus=RELOAD_PERSISTENCE, it means the message can only be durable
// even though the parsing hasn't happened yet
return getDataScanningStatus() == MessageDataScanningStatus.RELOAD_PERSISTENCE;
}
}
@Override
public final org.apache.activemq.artemis.api.core.Message setDurable(boolean durable) {
if (header == null) {
header = new Header();
}
header.setDurable(durable); // Message needs to be re-encoded following this action.
return this;
}
@Override
public final String getAddress() {
SimpleString addressSimpleString = getAddressSimpleString();
return addressSimpleString == null ? null : addressSimpleString.toString();
}
@Override
public final AMQPMessage setAddress(String address) {
setAddress(cachedAddressSimpleString(address));
return this;
}
@Override
public final AMQPMessage setAddress(SimpleString address) {
this.address = address;
createExtraProperties().putSimpleStringProperty(ADDRESS_PROPERTY, address);
return this;
}
final void reloadAddress(SimpleString address) {
this.address = address;
}
@Override
public final SimpleString getAddressSimpleString() {
if (address == null) {
TypedProperties extraProperties = getExtraProperties();
// we first check if extraProperties is not null, no need to create it just to check it here
if (extraProperties != null) {
address = extraProperties.getSimpleStringProperty(ADDRESS_PROPERTY);
}
if (address == null) {
// if it still null, it will look for the address on the getTo();
if (properties != null && properties.getTo() != null) {
address = cachedAddressSimpleString(properties.getTo());
}
}
}
return address;
}
protected SimpleString cachedAddressSimpleString(String address) {
return CoreMessageObjectPools.cachedAddressSimpleString(address, coreMessageObjectPools);
}
@Override
public final long getTimestamp() {
if (properties != null && properties.getCreationTime() != null) {
return properties.getCreationTime().getTime();
} else {
return 0L;
}
}
@Override
public final org.apache.activemq.artemis.api.core.Message setTimestamp(long timestamp) {
if (properties == null) {
properties = new Properties();
}
properties.setCreationTime(new Date(timestamp));
return this;
}
@Override
public final byte getPriority() {
if (header != null && header.getPriority() != null) {
return (byte) Math.min(header.getPriority().intValue(), MAX_MESSAGE_PRIORITY);
} else {
return DEFAULT_MESSAGE_PRIORITY;
}
}
@Override
public final org.apache.activemq.artemis.api.core.Message setPriority(byte priority) {
if (header == null) {
header = new Header();
}
header.setPriority(UnsignedByte.valueOf(priority));
return this;
}
@Override
public final SimpleString getReplyTo() {
if (properties != null) {
return SimpleString.toSimpleString(properties.getReplyTo());
} else {
return null;
}
}
@Override
public final AMQPMessage setReplyTo(SimpleString address) {
if (properties == null) {
properties = new Properties();
}
properties.setReplyTo(address != null ? address.toString() : null);
return this;
}
@Override
public final RoutingType getRoutingType() {
ensureMessageDataScanned();
Object routingType = getMessageAnnotation(AMQPMessageSupport.ROUTING_TYPE);
if (routingType != null) {
return RoutingType.getType(((Number) routingType).byteValue());
} else {
routingType = getMessageAnnotation(AMQPMessageSupport.JMS_DEST_TYPE_MSG_ANNOTATION);
if (routingType != null) {
if (AMQPMessageSupport.QUEUE_TYPE == ((Number) routingType).byteValue() || AMQPMessageSupport.TEMP_QUEUE_TYPE == ((Number) routingType).byteValue()) {
return RoutingType.ANYCAST;
} else if (AMQPMessageSupport.TOPIC_TYPE == ((Number) routingType).byteValue() || AMQPMessageSupport.TEMP_TOPIC_TYPE == ((Number) routingType).byteValue()) {
return RoutingType.MULTICAST;
}
} else {
return null;
}
return null;
}
}
@Override
public final org.apache.activemq.artemis.api.core.Message setRoutingType(RoutingType routingType) {
if (routingType == null) {
removeMessageAnnotation(AMQPMessageSupport.ROUTING_TYPE);
} else {
setMessageAnnotation(AMQPMessageSupport.ROUTING_TYPE, routingType.getType());
}
return this;
}
@Override
public final SimpleString getGroupID() {
ensureMessageDataScanned();
if (properties != null && properties.getGroupId() != null) {
return SimpleString.toSimpleString(properties.getGroupId(),
coreMessageObjectPools == null ? null : coreMessageObjectPools.getGroupIdStringSimpleStringPool());
} else {
return null;
}
}
@Override
public final int getGroupSequence() {
ensureMessageDataScanned();
if (properties != null && properties.getGroupSequence() != null) {
return properties.getGroupSequence().intValue();
} else {
return 0;
}
}
@Override
public final Object getCorrelationID() {
return properties != null ? properties.getCorrelationId() : null;
}
@Override
public final org.apache.activemq.artemis.api.core.Message setCorrelationID(final Object correlationID) {
if (properties == null) {
properties = new Properties();
}
properties.setCorrelationId(correlationID);
return this;
}
@Override
public boolean hasScheduledDeliveryTime() {
if (scheduledTime >= 0) {
return scheduledTime > 0;
}
return anyMessageAnnotations(SCHEDULED_DELIVERY_SYMBOLS, SCHEDULED_DELIVERY_NEEDLES);
}
private boolean anyMessageAnnotations(Symbol[] symbols, KMPNeedle[] symbolNeedles) {
assert symbols.length == symbolNeedles.length;
final int count = symbols.length;
if (messageDataScanned == MessageDataScanningStatus.SCANNED.code) {
final MessageAnnotations messageAnnotations = this.messageAnnotations;
if (messageAnnotations == null) {
return false;
}
Map<Symbol, Object> map = messageAnnotations.getValue();
if (map == null) {
return false;
}
for (int i = 0; i < count; i++) {
if (map.containsKey(symbols[i])) {
return true;
}
}
return false;
}
return AMQPMessageSymbolSearch.anyMessageAnnotations(getData(), symbolNeedles);
}
@Override
public final Long getScheduledDeliveryTime() {
ensureMessageDataScanned();
if (scheduledTime < 0) {
Object objscheduledTime = getMessageAnnotation(AMQPMessageSupport.SCHEDULED_DELIVERY_TIME);
Object objdelay = getMessageAnnotation(AMQPMessageSupport.SCHEDULED_DELIVERY_DELAY);
if (objscheduledTime != null && objscheduledTime instanceof Number) {
this.scheduledTime = ((Number) objscheduledTime).longValue();
} else if (objdelay != null && objdelay instanceof Number) {
this.scheduledTime = System.currentTimeMillis() + ((Number) objdelay).longValue();
} else {
this.scheduledTime = 0;
}
}
return scheduledTime;
}
@Override
public final AMQPMessage setScheduledDeliveryTime(Long time) {
if (time != null && time.longValue() > 0) {
setMessageAnnotation(AMQPMessageSupport.SCHEDULED_DELIVERY_TIME, time);
removeMessageAnnotation(AMQPMessageSupport.SCHEDULED_DELIVERY_DELAY);
scheduledTime = time;
} else {
removeMessageAnnotation(AMQPMessageSupport.SCHEDULED_DELIVERY_TIME);
removeMessageAnnotation(AMQPMessageSupport.SCHEDULED_DELIVERY_DELAY);
scheduledTime = 0;
}
return this;
}
@Override
public final Object removeAnnotation(SimpleString key) {
return removeMessageAnnotation(Symbol.getSymbol(key.toString()));
}
@Override
public final Object getAnnotation(SimpleString key) {
return getMessageAnnotation(key.toString());
}
@Override
public final AMQPMessage setAnnotation(SimpleString key, Object value) {
setMessageAnnotation(key.toString(), value);
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message setBrokerProperty(SimpleString key, Object value) {
// Annotation names have to start with x-opt
setMessageAnnotation(AMQPMessageSupport.toAnnotationName(key.toString()), value);
createExtraProperties().putProperty(key, value);
return this;
}
@Override
public Object getBrokerProperty(SimpleString key) {
TypedProperties extra = getExtraProperties();
if (extra == null) {
return null;
}
return extra.getProperty(key);
}
@Override
public final org.apache.activemq.artemis.api.core.Message setIngressTimestamp() {
setMessageAnnotation(AMQPMessageSupport.INGRESS_TIME_MSG_ANNOTATION, System.currentTimeMillis());
return this;
}
@Override
public Long getIngressTimestamp() {
return (Long) getMessageAnnotation(AMQPMessageSupport.INGRESS_TIME_MSG_ANNOTATION);
}
// JMS Style property access methods. These can result in additional decode of AMQP message
// data from Application properties. Updates to application properties puts the message in a
// dirty state and requires a re-encode of the data to update all buffer state data otherwise
// the next send of the Message will not include changes made here.
@Override
public final Object removeProperty(SimpleString key) {
return removeProperty(key.toString());
}
@Override
public final Object removeProperty(String key) {
return getApplicationPropertiesMap(false).remove(key);
}
@Override
public final boolean containsProperty(SimpleString key) {
return containsProperty(key.toString());
}
@Override
public final boolean containsProperty(String key) {
return getApplicationPropertiesMap(false).containsKey(key);
}
@Override
public final Boolean getBooleanProperty(String key) throws ActiveMQPropertyConversionException {
return (Boolean) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Byte getByteProperty(String key) throws ActiveMQPropertyConversionException {
return (Byte) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Double getDoubleProperty(String key) throws ActiveMQPropertyConversionException {
return (Double) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Integer getIntProperty(String key) throws ActiveMQPropertyConversionException {
return (Integer) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Long getLongProperty(String key) throws ActiveMQPropertyConversionException {
return (Long) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Object getObjectProperty(String key) {
switch (key) {
case MessageUtil.TYPE_HEADER_NAME_STRING:
if (properties != null) {
return properties.getSubject();
}
return null;
case MessageUtil.CONNECTION_ID_PROPERTY_NAME_STRING:
return getConnectionID();
case MessageUtil.JMSXGROUPID:
return getGroupID();
case MessageUtil.JMSXGROUPSEQ:
return getGroupSequence();
case MessageUtil.JMSXUSERID:
return getAMQPUserID();
case MessageUtil.CORRELATIONID_HEADER_NAME_STRING:
if (properties != null && properties.getCorrelationId() != null) {
return AMQPMessageIdHelper.INSTANCE.toCorrelationIdString(properties.getCorrelationId());
}
return null;
default:
return getApplicationObjectProperty(key);
}
}
private Object getApplicationObjectProperty(String key) {
Object value = getApplicationPropertiesMap(false).get(key);
if (value instanceof Number) {
// slow path
if (value instanceof UnsignedInteger ||
value instanceof UnsignedByte ||
value instanceof UnsignedLong ||
value instanceof UnsignedShort) {
return ((Number) value).longValue();
}
}
return value;
}
@Override
public final Short getShortProperty(String key) throws ActiveMQPropertyConversionException {
return (Short) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Float getFloatProperty(String key) throws ActiveMQPropertyConversionException {
return (Float) getApplicationPropertiesMap(false).get(key);
}
@Override
public final String getStringProperty(String key) throws ActiveMQPropertyConversionException {
switch (key) {
case MessageUtil.TYPE_HEADER_NAME_STRING:
return properties.getSubject();
case MessageUtil.CONNECTION_ID_PROPERTY_NAME_STRING:
return getConnectionID();
default:
return (String) getApplicationPropertiesMap(false).get(key);
}
}
@Override
public final Set<SimpleString> getPropertyNames() {
HashSet<SimpleString> values = new HashSet<>();
for (Object k : getApplicationPropertiesMap(false).keySet()) {
values.add(SimpleString.toSimpleString(k.toString(), getPropertyKeysPool()));
}
return values;
}
@Override
public final Boolean getBooleanProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getBooleanProperty(key.toString());
}
@Override
public final Byte getByteProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getByteProperty(key.toString());
}
@Override
public final byte[] getBytesProperty(String key) throws ActiveMQPropertyConversionException {
return (byte[]) getApplicationPropertiesMap(false).get(key);
}
@Override
public final Double getDoubleProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getDoubleProperty(key.toString());
}
@Override
public final Integer getIntProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getIntProperty(key.toString());
}
@Override
public final Long getLongProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getLongProperty(key.toString());
}
@Override
public final Object getObjectProperty(SimpleString key) {
return getObjectProperty(key.toString());
}
@Override
public final Short getShortProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getShortProperty(key.toString());
}
@Override
public final Float getFloatProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getFloatProperty(key.toString());
}
@Override
public final String getStringProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getStringProperty(key.toString());
}
@Override
public final SimpleString getSimpleStringProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getSimpleStringProperty(key.toString());
}
@Override
public final byte[] getBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getBytesProperty(key.toString());
}
@Override
public final SimpleString getSimpleStringProperty(String key) throws ActiveMQPropertyConversionException {
return SimpleString.toSimpleString((String) getApplicationPropertiesMap(false).get(key), getPropertyValuesPool());
}
// Core Message Application Property update methods, calling these puts the message in a dirty
// state and requires a re-encode of the data to update all buffer state data. If no re-encode
// is done prior to the next dispatch the old view of the message will be sent.
@Override
public final org.apache.activemq.artemis.api.core.Message putBooleanProperty(String key, boolean value) {
getApplicationPropertiesMap(true).put(key, Boolean.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putByteProperty(String key, byte value) {
getApplicationPropertiesMap(true).put(key, Byte.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putBytesProperty(String key, byte[] value) {
getApplicationPropertiesMap(true).put(key, value);
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putShortProperty(String key, short value) {
getApplicationPropertiesMap(true).put(key, Short.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putCharProperty(String key, char value) {
getApplicationPropertiesMap(true).put(key, Character.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putIntProperty(String key, int value) {
getApplicationPropertiesMap(true).put(key, Integer.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putLongProperty(String key, long value) {
getApplicationPropertiesMap(true).put(key, Long.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putFloatProperty(String key, float value) {
getApplicationPropertiesMap(true).put(key, Float.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putDoubleProperty(String key, double value) {
getApplicationPropertiesMap(true).put(key, Double.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putBooleanProperty(SimpleString key, boolean value) {
getApplicationPropertiesMap(true).put(key.toString(), Boolean.valueOf(value));
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putByteProperty(SimpleString key, byte value) {
return putByteProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putBytesProperty(SimpleString key, byte[] value) {
return putBytesProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putShortProperty(SimpleString key, short value) {
return putShortProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putCharProperty(SimpleString key, char value) {
return putCharProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putIntProperty(SimpleString key, int value) {
return putIntProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putLongProperty(SimpleString key, long value) {
return putLongProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putFloatProperty(SimpleString key, float value) {
return putFloatProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putDoubleProperty(SimpleString key, double value) {
return putDoubleProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putStringProperty(String key, String value) {
getApplicationPropertiesMap(true).put(key, value);
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putObjectProperty(String key, Object value) throws ActiveMQPropertyConversionException {
getApplicationPropertiesMap(true).put(key, value);
return this;
}
@Override
public final org.apache.activemq.artemis.api.core.Message putObjectProperty(SimpleString key, Object value) throws ActiveMQPropertyConversionException {
return putObjectProperty(key.toString(), value);
}
@Override
public final org.apache.activemq.artemis.api.core.Message putStringProperty(SimpleString key, SimpleString value) {
return putStringProperty(key.toString(), value.toString());
}
@Override
public final org.apache.activemq.artemis.api.core.Message putStringProperty(SimpleString key, String value) {
return putStringProperty(key.toString(), value);
}
@Override
public final SimpleString getLastValueProperty() {
return getSimpleStringProperty(HDR_LAST_VALUE_NAME);
}
@Override
public final org.apache.activemq.artemis.api.core.Message setLastValueProperty(SimpleString lastValueName) {
return putStringProperty(HDR_LAST_VALUE_NAME, lastValueName);
}
@Override
public String toString() {
MessageDataScanningStatus scanningStatus = getDataScanningStatus();
Map<String, Object> applicationProperties = scanningStatus == MessageDataScanningStatus.SCANNED ?
getApplicationPropertiesMap(false) : Collections.EMPTY_MAP;
return this.getClass().getSimpleName() + "( [durable=" + isDurable() +
", messageID=" + getMessageID() +
", address=" + getAddress() +
", size=" + getEncodeSize() +
", scanningStatus=" + scanningStatus +
", applicationProperties=" + applicationProperties +
", messageAnnotations=" + getMessageAnnotationsMap(false) +
", properties=" + properties +
", extraProperties = " + getExtraProperties() +
"]";
}
@Override
public final synchronized boolean acceptsConsumer(long consumer) {
if (rejectedConsumers == null) {
return true;
} else {
return !rejectedConsumers.contains(consumer);
}
}
@Override
public final synchronized void rejectConsumer(long consumer) {
if (rejectedConsumers == null) {
rejectedConsumers = new HashSet<>();
}
rejectedConsumers.add(consumer);
}
protected SimpleString.StringSimpleStringPool getPropertyKeysPool() {
return coreMessageObjectPools == null ? null : coreMessageObjectPools.getPropertiesStringSimpleStringPools().getPropertyKeysPool();
}
protected SimpleString.StringSimpleStringPool getPropertyValuesPool() {
return coreMessageObjectPools == null ? null : coreMessageObjectPools.getPropertiesStringSimpleStringPools().getPropertyValuesPool();
}
@Override
public Object getOwner() {
return owner;
}
@Override
public void setOwner(Object object) {
this.owner = object;
}
// *******************************************************************************************************************************
// Composite Data implementation
private static MessageOpenTypeFactory AMQP_FACTORY = new AmqpMessageOpenTypeFactory();
static class AmqpMessageOpenTypeFactory extends MessageOpenTypeFactory<AMQPMessage> {
@Override
protected void init() throws OpenDataException {
super.init();
addItem(CompositeDataConstants.TEXT_BODY, CompositeDataConstants.TEXT_BODY, SimpleType.STRING);
}
@Override
public Map<String, Object> getFields(AMQPMessage m, int valueSizeLimit, int delivery) throws OpenDataException {
if (!m.isLargeMessage()) {
m.ensureScanning();
}
Map<String, Object> rc = super.getFields(m, valueSizeLimit, delivery);
Properties properties = m.getCurrentProperties();
byte type = getType(m, properties);
rc.put(CompositeDataConstants.TYPE, type);
if (m.isLargeMessage()) {
rc.put(CompositeDataConstants.TEXT_BODY, "... Large message ...");
} else {
Object amqpValue;
if (m.getBody() instanceof AmqpValue && (amqpValue = ((AmqpValue) m.getBody()).getValue()) != null) {
rc.put(CompositeDataConstants.TEXT_BODY, JsonUtil.truncateString(String.valueOf(amqpValue), valueSizeLimit));
} else {
rc.put(CompositeDataConstants.TEXT_BODY, JsonUtil.truncateString(String.valueOf(m.getBody()), valueSizeLimit));
}
}
return rc;
}
@Override
protected Map<String, Object> expandProperties(AMQPMessage m, int valueSizeLimit) {
return m.toPropertyMap(true, valueSizeLimit);
}
private byte getType(AMQPMessage m, Properties properties) {
if (m.isLargeMessage()) {
return DEFAULT_TYPE;
}
byte type = BYTES_TYPE;
if (m.getBody() == null) {
return DEFAULT_TYPE;
}
final Symbol contentType = properties != null ? properties.getContentType() : null;
if (m.getBody() instanceof Data && contentType != null) {
if (AMQPMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE.equals(contentType)) {
type = OBJECT_TYPE;
} else if (AMQPMessageSupport.OCTET_STREAM_CONTENT_TYPE_SYMBOL.equals(contentType)) {
type = BYTES_TYPE;
} else {
Charset charset = getCharsetForTextualContent(contentType.toString());
if (StandardCharsets.UTF_8.equals(charset)) {
type = TEXT_TYPE;
}
}
} else if (m.getBody() instanceof AmqpValue) {
Object value = ((AmqpValue) m.getBody()).getValue();
if (value instanceof String) {
type = TEXT_TYPE;
} else if (value instanceof Binary) {
if (AMQPMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE.equals(contentType)) {
type = OBJECT_TYPE;
} else {
type = BYTES_TYPE;
}
} else if (value instanceof List) {
type = STREAM_TYPE;
} else if (value instanceof Map) {
type = MAP_TYPE;
}
} else if (m.getBody() instanceof AmqpSequence) {
type = STREAM_TYPE;
}
return type;
}
}
@Override
public CompositeData toCompositeData(int fieldsLimit, int deliveryCount) throws OpenDataException {
Map<String, Object> fields;
fields = AMQP_FACTORY.getFields(this, fieldsLimit, deliveryCount);
return new CompositeDataSupport(AMQP_FACTORY.getCompositeType(), fields);
}
// Composite Data implementation
// *******************************************************************************************************************************
} | This closes #4071
| artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPMessage.java | This closes #4071 | <ide><path>rtemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPMessage.java
<ide> if (properties.getSubject() != null) {
<ide> map.put(propertiesPrefix + "subject", properties.getSubject());
<ide> }
<add> if (properties.getReplyTo() != null) {
<add> map.put(propertiesPrefix + "replyTo", properties.getReplyTo());
<add> }
<ide> }
<ide>
<ide> return map; |
|
JavaScript | mit | af11774664807e5ddee63ae5742b3c9c9153c2dc | 0 | sweavo/jiraMonkey | // ==UserScript==
// @name JIRA Quicksearch plus
// @namespace https://github.com/sweavo/jiraMonkey
// @version 1.0
// @description Quicksearch to use current project and unresolved only. Inspired by https://jira.atlassian.com/browse/JRA-15306
// @author [email protected]
// @include /^https?:\/\/HOSTNAME:8080/
// @grant none
// @run-at document-end
// ==/UserScript==
//
// To install:
// open tamperMonkey dashboard,
// create a new script,
// paste this whole file over the whole edit buffer
// edit HOSTNAME above to the hostname of your JIRA server
// update the port 8080 if necessary
// set your project name below.
var PROJECT_NAME="UPDATEME";
// TamperMonkey executes this script on DOMContentLoaded
var quicksearch = document.getElementById("quicksearch");
var qsInput = document.getElementById("quickSearchInput");
function dress_qs_as_jql( qs )
{
return 'text ~ "' + qs + '"' +
' and resolution is EMPTY' +
' and project="' + PROJECT_NAME + '"';
}
function jm_submit_quicksearch( )
{
RE_INT= /^\d+$/;
// If numeric, don't futz with the field
if ( RE_INT.test( qsInput.value ) )
{
return;
}
// Else we will restrict the project and resolution
qsInput.value = dress_qs_as_jql( qsInput.value );
qsInput.name="jql"; // No longer submitting quickSearch, but advanced
}
// Override the search box behavior and mouseover hint
quicksearch.addEventListener( "submit", jm_submit_quicksearch );
// Advertise that we've overridden the behavior
qsInput.placeholder="S.U.I.P.";
qsInput.title="Search unresolved tickets in project " + PROJECT_NAME + " (Type '/')";
| jira_quicksearch_customize.js | // ==UserScript==
// @name JIRA Quicksearch plus
// @namespace https://github.com/sweavo/jiraMonkey
// @version 1.0
// @description Quicksearch to use current project and unresolved only. Inspired by https://jira.atlassian.com/browse/JRA-15306
// @author [email protected]
// @include /^https?:\/\/HOSTNAME:8080/
// @grant none
// @run-at document-end
// ==/UserScript==
//
// To install:
// open tamperMonkey dashboard,
// create a new script,
// paste this whole file over the whole edit buffer
// edit HOSTNAME above to the hostname of your JIRA server
// update the port 8080 if necessary
// set your project name below.
var PROJECT_NAME="UPDATEME";
function dress_qs_as_jql( qs )
{
RE_INT= /^\d+$/;
if ( RE_INT.test( qs ) )
{
return 'issueID = ' + qs + ' and project="' + PROJECT_NAME + '"';
}
else
{
return 'text ~ "' + qs + '"' +
' and resolution is EMPTY' +
' and project="' + PROJECT_NAME + '"';
}
}
// TamperMonkey executes this script on DOMContentLoaded
var quicksearch = document.getElementById("quicksearch");
var qsInput = document.getElementById("quickSearchInput");
// Override the search box behavior and mouseover hint
quicksearch.addEventListener("submit",function(){ qsInput.value = dress_qs_as_jql( qsInput.value ); });
qsInput.name="jql"; // No longer submitting quickSearch, but advanced
// Advertise that we've overridden the behavior
qsInput.placeholder="S.U.I.P.";
qsInput.title="Search unresolved tickets in project " + PROJECT_NAME + " (Type '/')";
| Tested and fixed numerical quicksearch
| jira_quicksearch_customize.js | Tested and fixed numerical quicksearch | <ide><path>ira_quicksearch_customize.js
<ide> // set your project name below.
<ide> var PROJECT_NAME="UPDATEME";
<ide>
<del>function dress_qs_as_jql( qs )
<del>{
<del> RE_INT= /^\d+$/;
<del> if ( RE_INT.test( qs ) )
<del> {
<del> return 'issueID = ' + qs + ' and project="' + PROJECT_NAME + '"';
<del> }
<del> else
<del> {
<del> return 'text ~ "' + qs + '"' +
<del> ' and resolution is EMPTY' +
<del> ' and project="' + PROJECT_NAME + '"';
<del> }
<del>}
<del>
<ide> // TamperMonkey executes this script on DOMContentLoaded
<ide> var quicksearch = document.getElementById("quicksearch");
<ide> var qsInput = document.getElementById("quickSearchInput");
<ide>
<add>function dress_qs_as_jql( qs )
<add>{
<add> return 'text ~ "' + qs + '"' +
<add> ' and resolution is EMPTY' +
<add> ' and project="' + PROJECT_NAME + '"';
<add>}
<add>
<add>function jm_submit_quicksearch( )
<add>{
<add> RE_INT= /^\d+$/;
<add> // If numeric, don't futz with the field
<add> if ( RE_INT.test( qsInput.value ) )
<add> {
<add> return;
<add> }
<add>
<add> // Else we will restrict the project and resolution
<add> qsInput.value = dress_qs_as_jql( qsInput.value );
<add> qsInput.name="jql"; // No longer submitting quickSearch, but advanced
<add>}
<add>
<add>
<ide> // Override the search box behavior and mouseover hint
<del>quicksearch.addEventListener("submit",function(){ qsInput.value = dress_qs_as_jql( qsInput.value ); });
<del>qsInput.name="jql"; // No longer submitting quickSearch, but advanced
<add>quicksearch.addEventListener( "submit", jm_submit_quicksearch );
<ide>
<ide> // Advertise that we've overridden the behavior
<ide> qsInput.placeholder="S.U.I.P."; |
|
Java | apache-2.0 | 47b5343a7516296c37fc1f29192341dcc8ed7d21 | 0 | UweTrottmann/SeriesGuide,UweTrottmann/SeriesGuide,epiphany27/SeriesGuide | package com.battlelancer.seriesguide;
import android.app.Activity;
import android.app.Application;
import android.content.ContentProvider;
import android.os.Build;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.os.StrictMode.VmPolicy;
import com.battlelancer.seriesguide.modules.AppModule;
import com.battlelancer.seriesguide.modules.DaggerServicesComponent;
import com.battlelancer.seriesguide.modules.HttpClientModule;
import com.battlelancer.seriesguide.modules.ServicesComponent;
import com.battlelancer.seriesguide.modules.TmdbModule;
import com.battlelancer.seriesguide.modules.TraktModule;
import com.battlelancer.seriesguide.modules.TvdbModule;
import com.battlelancer.seriesguide.settings.AppSettings;
import com.battlelancer.seriesguide.settings.DisplaySettings;
import com.battlelancer.seriesguide.util.ThemeUtils;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.analytics.GoogleAnalytics;
import io.fabric.sdk.android.Fabric;
import net.danlew.android.joda.JodaTimeAndroid;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.EventBusException;
import timber.log.Timber;
/**
* Initializes settings and services and on pre-ICS implements actions for low memory state.
*
* @author Uwe Trottmann
*/
public class SgApp extends Application {
public static final int NOTIFICATION_EPISODE_ID = 1;
public static final int NOTIFICATION_SUBSCRIPTION_ID = 2;
public static final int NOTIFICATION_TRAKT_AUTH_ID = 3;
/**
* Time calculation has changed, all episodes need re-calculation.
*/
public static final int RELEASE_VERSION_12_BETA5 = 218;
/**
* Requires legacy cache clearing due to switch to Picasso for posters.
*/
public static final int RELEASE_VERSION_16_BETA1 = 15010;
/**
* Requires trakt watched movie (re-)download.
*/
public static final int RELEASE_VERSION_23_BETA4 = 15113;
/**
* Requires full show update due to switch to locally stored trakt ids.
*/
public static final int RELEASE_VERSION_26_BETA3 = 15142;
/**
* The content authority used to identify the SeriesGuide {@link ContentProvider}
*/
public static final String CONTENT_AUTHORITY = BuildConfig.APPLICATION_ID + ".provider";
private ServicesComponent servicesComponent;
@Override
public void onCreate() {
super.onCreate();
// logging setup
if (BuildConfig.DEBUG) {
// detailed logcat logging
Timber.plant(new Timber.DebugTree());
} else {
// crash and error reporting
Timber.plant(new AnalyticsTree(this));
if (!Fabric.isInitialized()) {
Fabric.with(this, new Crashlytics());
}
}
// initialize EventBus
try {
EventBus.builder().addIndex(new SgEventBusIndex()).installDefaultEventBus();
} catch (EventBusException e) {
// looks like instance sometimes still lingers around,
// so far happening from services, though no exact cause found, yet
Timber.e(e, "EventBus already installed.");
}
// initialize joda-time-android
JodaTimeAndroid.init(this);
// Load the current theme into a global variable
ThemeUtils.updateTheme(DisplaySettings.getThemeIndex(this));
// Ensure GA opt-out
GoogleAnalytics.getInstance(this).setAppOptOut(AppSettings.isGaAppOptOut(this));
if (BuildConfig.DEBUG) {
GoogleAnalytics.getInstance(this).setDryRun(true);
}
// Initialize tracker
Analytics.getTracker(this);
enableStrictMode();
servicesComponent = DaggerServicesComponent.builder()
.appModule(new AppModule(this))
.httpClientModule(new HttpClientModule())
.tmdbModule(new TmdbModule())
.traktModule(new TraktModule())
.tvdbModule(new TvdbModule())
.build();
}
public static SgApp from(Activity activity) {
return (SgApp) activity.getApplication();
}
public ServicesComponent getServicesComponent() {
return servicesComponent;
}
/**
* Used to enable {@link StrictMode} for debug builds.
*/
private static void enableStrictMode() {
if (!BuildConfig.DEBUG) {
return;
}
// Enable StrictMode
final ThreadPolicy.Builder threadPolicyBuilder = new ThreadPolicy.Builder();
threadPolicyBuilder.detectAll();
threadPolicyBuilder.penaltyLog();
StrictMode.setThreadPolicy(threadPolicyBuilder.build());
// Policy applied to all threads in the virtual machine's process
final VmPolicy.Builder vmPolicyBuilder = new VmPolicy.Builder();
vmPolicyBuilder.detectAll();
vmPolicyBuilder.penaltyLog();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
vmPolicyBuilder.detectLeakedRegistrationObjects();
}
StrictMode.setVmPolicy(vmPolicyBuilder.build());
}
}
| SeriesGuide/src/main/java/com/battlelancer/seriesguide/SgApp.java | package com.battlelancer.seriesguide;
import android.app.Activity;
import android.app.Application;
import android.content.ContentProvider;
import android.os.Build;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.os.StrictMode.VmPolicy;
import com.battlelancer.seriesguide.modules.AppModule;
import com.battlelancer.seriesguide.modules.DaggerServicesComponent;
import com.battlelancer.seriesguide.modules.HttpClientModule;
import com.battlelancer.seriesguide.modules.ServicesComponent;
import com.battlelancer.seriesguide.modules.TmdbModule;
import com.battlelancer.seriesguide.modules.TraktModule;
import com.battlelancer.seriesguide.modules.TvdbModule;
import com.battlelancer.seriesguide.settings.AppSettings;
import com.battlelancer.seriesguide.settings.DisplaySettings;
import com.battlelancer.seriesguide.util.ThemeUtils;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.analytics.GoogleAnalytics;
import io.fabric.sdk.android.Fabric;
import net.danlew.android.joda.JodaTimeAndroid;
import org.greenrobot.eventbus.EventBus;
import timber.log.Timber;
/**
* Initializes settings and services and on pre-ICS implements actions for low memory state.
*
* @author Uwe Trottmann
*/
public class SgApp extends Application {
public static final int NOTIFICATION_EPISODE_ID = 1;
public static final int NOTIFICATION_SUBSCRIPTION_ID = 2;
public static final int NOTIFICATION_TRAKT_AUTH_ID = 3;
/**
* Time calculation has changed, all episodes need re-calculation.
*/
public static final int RELEASE_VERSION_12_BETA5 = 218;
/**
* Requires legacy cache clearing due to switch to Picasso for posters.
*/
public static final int RELEASE_VERSION_16_BETA1 = 15010;
/**
* Requires trakt watched movie (re-)download.
*/
public static final int RELEASE_VERSION_23_BETA4 = 15113;
/**
* Requires full show update due to switch to locally stored trakt ids.
*/
public static final int RELEASE_VERSION_26_BETA3 = 15142;
/**
* The content authority used to identify the SeriesGuide {@link ContentProvider}
*/
public static final String CONTENT_AUTHORITY = BuildConfig.APPLICATION_ID + ".provider";
private ServicesComponent servicesComponent;
@Override
public void onCreate() {
super.onCreate();
// logging setup
if (BuildConfig.DEBUG) {
// detailed logcat logging
Timber.plant(new Timber.DebugTree());
} else {
// crash and error reporting
Timber.plant(new AnalyticsTree(this));
if (!Fabric.isInitialized()) {
Fabric.with(this, new Crashlytics());
}
}
// initialize EventBus
EventBus.builder().addIndex(new SgEventBusIndex()).installDefaultEventBus();
// initialize joda-time-android
JodaTimeAndroid.init(this);
// Load the current theme into a global variable
ThemeUtils.updateTheme(DisplaySettings.getThemeIndex(this));
// Ensure GA opt-out
GoogleAnalytics.getInstance(this).setAppOptOut(AppSettings.isGaAppOptOut(this));
if (BuildConfig.DEBUG) {
GoogleAnalytics.getInstance(this).setDryRun(true);
}
// Initialize tracker
Analytics.getTracker(this);
enableStrictMode();
servicesComponent = DaggerServicesComponent.builder()
.appModule(new AppModule(this))
.httpClientModule(new HttpClientModule())
.tmdbModule(new TmdbModule())
.traktModule(new TraktModule())
.tvdbModule(new TvdbModule())
.build();
}
public static SgApp from(Activity activity) {
return (SgApp) activity.getApplication();
}
public ServicesComponent getServicesComponent() {
return servicesComponent;
}
/**
* Used to enable {@link StrictMode} for debug builds.
*/
private static void enableStrictMode() {
if (!BuildConfig.DEBUG) {
return;
}
// Enable StrictMode
final ThreadPolicy.Builder threadPolicyBuilder = new ThreadPolicy.Builder();
threadPolicyBuilder.detectAll();
threadPolicyBuilder.penaltyLog();
StrictMode.setThreadPolicy(threadPolicyBuilder.build());
// Policy applied to all threads in the virtual machine's process
final VmPolicy.Builder vmPolicyBuilder = new VmPolicy.Builder();
vmPolicyBuilder.detectAll();
vmPolicyBuilder.penaltyLog();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
vmPolicyBuilder.detectLeakedRegistrationObjects();
}
StrictMode.setVmPolicy(vmPolicyBuilder.build());
}
}
| Do not crash on existing EventBus instance.
- https://fabric.io/seriesguide/android/apps/com.battlelancer.seriesguide/issues/57f541c70aeb16625b2c524c
- Looks like it can not be ensured that the EventBus instance is always gone when starting services. Might want to keep our own instance in the future inside SgApp.
| SeriesGuide/src/main/java/com/battlelancer/seriesguide/SgApp.java | Do not crash on existing EventBus instance. | <ide><path>eriesGuide/src/main/java/com/battlelancer/seriesguide/SgApp.java
<ide> import io.fabric.sdk.android.Fabric;
<ide> import net.danlew.android.joda.JodaTimeAndroid;
<ide> import org.greenrobot.eventbus.EventBus;
<add>import org.greenrobot.eventbus.EventBusException;
<ide> import timber.log.Timber;
<ide>
<ide> /**
<ide> }
<ide>
<ide> // initialize EventBus
<del> EventBus.builder().addIndex(new SgEventBusIndex()).installDefaultEventBus();
<add> try {
<add> EventBus.builder().addIndex(new SgEventBusIndex()).installDefaultEventBus();
<add> } catch (EventBusException e) {
<add> // looks like instance sometimes still lingers around,
<add> // so far happening from services, though no exact cause found, yet
<add> Timber.e(e, "EventBus already installed.");
<add> }
<ide>
<ide> // initialize joda-time-android
<ide> JodaTimeAndroid.init(this); |
|
Java | apache-2.0 | 94a3f90f4097ff3934591e22c5d63556b04fbf0f | 0 | arenadata/ambari,arenadata/ambari,alexryndin/ambari,alexryndin/ambari,alexryndin/ambari,arenadata/ambari,alexryndin/ambari,arenadata/ambari,alexryndin/ambari,arenadata/ambari,alexryndin/ambari,arenadata/ambari,arenadata/ambari,alexryndin/ambari,arenadata/ambari,alexryndin/ambari,alexryndin/ambari,arenadata/ambari,arenadata/ambari,alexryndin/ambari,alexryndin/ambari,arenadata/ambari | /**
* 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.ambari.server.state.services;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.ambari.server.AmbariService;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.controller.jmx.JMXMetricHolder;
import org.apache.ambari.server.controller.utilities.ScalingThreadPoolExecutor;
import org.apache.ambari.server.controller.utilities.StreamProvider;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.AbstractService;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.inject.Inject;
/**
* The {@link MetricsRetrievalService} is used as a headless, autonomous service
* which encapsulates:
* <ul>
* <li>An {@link ExecutorService} for fullfilling remote metric URL requests
* <li>A cache for JMX metrics
* <li>A cache for REST metrics
* </ul>
*
* Classes can inject an instance of this service in order to gain access to its
* caches and request mechanism.
* <p/>
* Callers must submit a request to the service in order to reach out and pull
* in remote metric data. Otherwise, the cache will never be populated. On the
* first usage of this service, the cache will always be empty. On every
* subsequent request, the data from the prior invocation of
* {@link #submitRequest(MetricSourceType, StreamProvider, String)} will be available.
* <p/>
* Metric data is cached temporarily and is controlled by
* {@link Configuration#getMetricsServiceCacheTimeout()}.
* <p/>
* In order to control throttling requests to the same endpoint,
* {@link Configuration#isMetricsServiceRequestTTLCacheEnabled()} can be enabled
* to allow for a fixed interval of time to pass between requests.
*/
@AmbariService
public class MetricsRetrievalService extends AbstractService {
/**
* The type of web service hosting the metrics.
*/
public enum MetricSourceType {
/**
* JMX
*/
JMX,
/**
* REST
*/
REST
}
/**
* Logger.
*/
protected final static Logger LOG = LoggerFactory.getLogger(MetricsRetrievalService.class);
/**
* The timeout for exceptions which are caught and then cached to prevent log
* spamming.
*
* @see #s_exceptionCache
*/
private static final int EXCEPTION_CACHE_TIMEOUT_MINUTES = 20;
/**
* Exceptions from this service should not SPAM the logs; so cache exceptions
* and log once every {@vale #EXCEPTION_CACHE_TIMEOUT_MINUTES} minutes.
*/
private static final Cache<String, Throwable> s_exceptionCache = CacheBuilder.newBuilder().expireAfterWrite(
EXCEPTION_CACHE_TIMEOUT_MINUTES, TimeUnit.MINUTES).build();
/**
* Configuration.
*/
@Inject
private Configuration m_configuration;
/**
* Used for reading REST JSON responses.
*/
@Inject
private Gson m_gson;
/**
* A cache of URL to parsed JMX beans
*/
private Cache<String, JMXMetricHolder> m_jmxCache;
/**
* A cache of URL to parsed REST data.
*/
private Cache<String, Map<String, String>> m_restCache;
/**
* The {@link Executor} which will handle all of the requests to load remote
* metrics from URLs.
*/
private ThreadPoolExecutor m_threadPoolExecutor;
/**
* Used to parse remote JMX JSON into a {@link Map}.
*/
private final ObjectReader m_jmxObjectReader;
/**
* A thread-safe collection of all of the URL endpoints queued for processing.
* This helps prevent the same endpoint from being queued multiple times.
*/
private final Set<String> m_queuedUrls = Sets.newConcurrentHashSet();
/**
* An evicting cache which ensures that multiple requests for the same
* endpoint are not executed back-to-back. When enabled, a fixed period of
* time must pass before this service will make requests to a previously
* retrieved endpoint.
* <p/>
* If this cache is not enabled, then it will be {@code null}.
* <p/>
* For simplicity, this is a cache of URL to URL.
*/
private Cache<String, String> m_ttlUrlCache;
/**
* The size of the worker queue (used for logged warnings about size).
*/
private int m_queueMaximumSize;
/**
* Constructor.
*
*/
public MetricsRetrievalService() {
ObjectMapper jmxObjectMapper = new ObjectMapper();
jmxObjectMapper.configure(DeserializationConfig.Feature.USE_ANNOTATIONS, false);
m_jmxObjectReader = jmxObjectMapper.reader(JMXMetricHolder.class);
}
/**
* {@inheritDoc}
*/
@Override
protected void doStart() {
// initialize the caches
int jmxCacheExpirationMinutes = m_configuration.getMetricsServiceCacheTimeout();
m_jmxCache = CacheBuilder.newBuilder().expireAfterWrite(jmxCacheExpirationMinutes,
TimeUnit.MINUTES).build();
m_restCache = CacheBuilder.newBuilder().expireAfterWrite(jmxCacheExpirationMinutes,
TimeUnit.MINUTES).build();
// enable the TTL cache if configured; otherwise leave it as null
int ttlSeconds = m_configuration.getMetricsServiceRequestTTL();
boolean ttlCacheEnabled = m_configuration.isMetricsServiceRequestTTLCacheEnabled();
if (ttlCacheEnabled) {
m_ttlUrlCache = CacheBuilder.newBuilder().expireAfterWrite(ttlSeconds,
TimeUnit.SECONDS).build();
}
// iniitalize the executor service
int corePoolSize = m_configuration.getMetricsServiceThreadPoolCoreSize();
int maxPoolSize = m_configuration.getMetricsServiceThreadPoolMaxSize();
m_queueMaximumSize = m_configuration.getMetricsServiceWorkerQueueSize();
int threadPriority = m_configuration.getMetricsServiceThreadPriority();
m_threadPoolExecutor = new ScalingThreadPoolExecutor(corePoolSize, maxPoolSize, 30,
TimeUnit.SECONDS, m_queueMaximumSize);
m_threadPoolExecutor.allowCoreThreadTimeOut(true);
m_threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(
"ambari-metrics-retrieval-service-thread-%d").setPriority(
threadPriority).setUncaughtExceptionHandler(
new MetricRunnableExceptionHandler()).build();
m_threadPoolExecutor.setThreadFactory(threadFactory);
LOG.info(
"Initializing the Metrics Retrieval Service with core={}, max={}, workerQueue={}, threadPriority={}",
corePoolSize, maxPoolSize, m_queueMaximumSize, threadPriority);
if (ttlCacheEnabled) {
LOG.info("Metrics Retrieval Service request TTL cache is enabled and set to {} seconds",
ttlSeconds);
}
}
/**
* Testing method for setting a synchronous {@link ThreadPoolExecutor}.
*
* @param threadPoolExecutor
*/
public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
m_threadPoolExecutor = threadPoolExecutor;
}
/**
* {@inheritDoc}
*/
@Override
protected void doStop() {
m_jmxCache.invalidateAll();
m_restCache.invalidateAll();
if (null != m_ttlUrlCache) {
m_ttlUrlCache.invalidateAll();
}
m_queuedUrls.clear();
m_threadPoolExecutor.shutdownNow();
}
/**
* Submit a {@link Runnable} for execution which retrieves metric data from
* the supplied endpoint. This will run inside of an {@link ExecutorService}
* to retrieve metric data from a URL endpoint and parse the result into a
* cached value.
* <p/>
* Once metric data is retrieved it is cached. Data in the cache can be
* retrieved via {@link #getCachedJMXMetric(String)} or
* {@link #getCachedRESTMetric(String)}, depending on the type of metric
* requested.
* <p/>
* Callers need not worry about invoking this mulitple times for the same URL
* endpoint. A single endpoint will only be enqueued once regardless of how
* many times this method is called until it has been fully retrieved and
* parsed. If the last endpoint request was too recent, then this method will
* opt to not make another call until the TTL period expires.
*
* @param type
* the type of service hosting the metric (not {@code null}).
* @param streamProvider
* the {@link StreamProvider} to use to read from the remote
* endpoint.
* @param jmxUrl
* the URL to read from
*
* @see #getCachedJMXMetric(String)
*/
public void submitRequest(MetricSourceType type, StreamProvider streamProvider, String url) {
// check to ensure that the request isn't already queued
if (m_queuedUrls.contains(url)) {
return;
}
// check to ensure that the request wasn't made too recently
if (null != m_ttlUrlCache && null != m_ttlUrlCache.getIfPresent(url)) {
return;
}
// log warnings if the queue size seems to be rather large
BlockingQueue<Runnable> queue = m_threadPoolExecutor.getQueue();
int queueSize = queue.size();
if (queueSize > Math.floor(0.9f * m_queueMaximumSize)) {
LOG.warn("The worker queue contains {} work items and is at {}% of capacity", queueSize,
((float) queueSize / m_queueMaximumSize) * 100);
}
// enqueue this URL
m_queuedUrls.add(url);
Runnable runnable = null;
switch (type) {
case JMX:
runnable = new JMXRunnable(m_jmxCache, m_queuedUrls, m_ttlUrlCache, m_jmxObjectReader,
streamProvider, url);
break;
case REST:
runnable = new RESTRunnable(m_restCache, m_queuedUrls, m_ttlUrlCache, m_gson,
streamProvider, url);
break;
default:
LOG.warn("Unable to retrieve metrics for the unknown type {}", type);
break;
}
if (null != runnable) {
m_threadPoolExecutor.execute(runnable);
}
}
/**
* Gets a cached JMX metric in the form of a {@link JMXMetricHolder}. If there
* is no metric data cached for the given URL, then {@code null} is returned.
* <p/>
* The onky way this cache is populated is by requesting the data to be loaded
* asynchronously via
* {@link #submitRequest(MetricSourceType, StreamProvider, String)} with the
* {@link MetricSourceType#JMX} type.
*
* @param jmxUrl
* the URL to retrieve cached data for (not {@code null}).
* @return the metric, or {@code null} if none.
*/
public JMXMetricHolder getCachedJMXMetric(String jmxUrl) {
return m_jmxCache.getIfPresent(jmxUrl);
}
/**
* Gets a cached REST metric in the form of a {@link Map}. If there is no
* metric data cached for the given URL, then {@code null} is returned.
* <p/>
* The onky way this cache is populated is by requesting the data to be loaded
* asynchronously via
* {@link #submitRequest(MetricSourceType, StreamProvider, String)} with the
* {@link MetricSourceType#REST} type.
*
* @param restUrl
* the URL to retrieve cached data for (not {@code null}).
* @return the metric, or {@code null} if none.
*/
public Map<String, String> getCachedRESTMetric(String restUrl) {
return m_restCache.getIfPresent(restUrl);
}
/**
* Encapsulates the common logic for all metric {@link Runnable} instnaces.
*/
private static abstract class MetricRunnable implements Runnable {
/**
* An initialized stream provider to read the remote endpoint.
*/
protected final StreamProvider m_streamProvider;
/**
* A fully-qualified URL to read from.
*/
protected final String m_url;
/**
* The URLs which have been requested but not yet read.
*/
private final Set<String> m_queuedUrls;
/**
* An evicting cache used to control whether a request for a metric can be
* made or if it is too soon after the last request.
*/
private final Cache<String, String> m_ttlUrlCache;
/**
* Constructor.
*
* @param streamProvider
* the stream provider to read the URL with
* @param url
* the URL endpoint to read data from (JMX or REST)
* @param queuedUrls
* the URLs which are currently waiting to be processed. This
* method will remove the specified URL from this {@link Set} when
* it completes (successful or not).
* @param m_ttlUrlCache
* an evicting cache which is used to determine if a request for a
* metric is too soon after the last request, or {@code null} if
* requests can be made sequentially without any separation.
*/
private MetricRunnable(StreamProvider streamProvider, String url, Set<String> queuedUrls,
Cache<String, String> ttlUrlCache) {
m_streamProvider = streamProvider;
m_url = url;
m_queuedUrls = queuedUrls;
m_ttlUrlCache = ttlUrlCache;
}
/**
* {@inheritDoc}
*/
@Override
public final void run() {
// provide some profiling
long startTime = 0;
long endTime = 0;
boolean isDebugEnabled = LOG.isDebugEnabled();
if (isDebugEnabled) {
startTime = System.currentTimeMillis();
}
InputStream inputStream = null;
try {
if (isDebugEnabled) {
endTime = System.currentTimeMillis();
LOG.debug("Loading metric JSON from {} took {}ms", m_url, (endTime - startTime));
}
// read the stream and process it
inputStream = m_streamProvider.readFrom(m_url);
processInputStreamAndCacheResult(inputStream);
// cache the URL, but only after successful parsing of the response
if (null != m_ttlUrlCache) {
m_ttlUrlCache.put(m_url, m_url);
}
} catch (Exception exception) {
logException(exception, m_url);
} finally {
IOUtils.closeQuietly(inputStream);
// remove this URL from the list of queued URLs to ensure it will be
// requested again
m_queuedUrls.remove(m_url);
}
}
/**
* Reads data from the specified {@link InputStream} and processes that into
* a cachable value. The value will then be cached by this method.
*
* @param inputStream
* @throws Exception
*/
protected abstract void processInputStreamAndCacheResult(InputStream inputStream)
throws Exception;
/**
* Logs the exception for the URL exactly once and caches the fact that the
* exception was logged. This is to prevent an endpoint being down from
* spamming the logs.
*
* @param throwable
* the exception to log (not {@code null}).
* @param url
* the URL associated with the exception (not {@code null}).
*/
final void logException(Throwable throwable, String url) {
String cacheKey = buildCacheKey(throwable, url);
if (null == s_exceptionCache.getIfPresent(cacheKey)) {
// cache it and log it
s_exceptionCache.put(cacheKey, throwable);
LOG.error(
"Unable to retrieve metrics from {}. Subsequent failures will be suppressed from the log for {} minutes.",
url, EXCEPTION_CACHE_TIMEOUT_MINUTES, throwable);
}
}
/**
* Builds a unique cache key for the combination of {@link Throwable} and
* {@link String} URL.
*
* @param throwable
* @param url
* @return the key, such as {@value IOException-http://www.server.com/jmx}.
*/
private String buildCacheKey(Throwable throwable, String url) {
if (null == throwable || null == url) {
return "";
}
String throwableName = throwable.getClass().getSimpleName();
return throwableName + "-" + url;
}
}
/**
* A {@link Runnable} used to retrieve JMX data from a remote URL endpoint.
* There is no need for a {@link Callable} here since the
* {@link MetricsRetrievalService} doesn't care about when the value returns or
* whether an exception is thrown.
*/
private static final class JMXRunnable extends MetricRunnable {
private final ObjectReader m_jmxObjectReader;
private final Cache<String, JMXMetricHolder> m_cache;
/**
* Constructor.
*
* @param cache
* @param queuedUrls
* @param ttlUrlCache
* @param jmxObjectReader
* @param streamProvider
* @param jmxUrl
*/
private JMXRunnable(Cache<String, JMXMetricHolder> cache, Set<String> queuedUrls,
Cache<String, String> ttlUrlCache, ObjectReader jmxObjectReader,
StreamProvider streamProvider, String jmxUrl) {
super(streamProvider, jmxUrl, queuedUrls, ttlUrlCache);
m_cache = cache;
m_jmxObjectReader = jmxObjectReader;
}
/**
* {@inheritDoc}
*/
@Override
protected void processInputStreamAndCacheResult(InputStream inputStream) throws Exception {
JMXMetricHolder jmxMetricHolder = m_jmxObjectReader.readValue(inputStream);
m_cache.put(m_url, jmxMetricHolder);
}
}
/**
* A {@link Runnable} used to retrieve REST data from a remote URL endpoint.
* There is no need for a {@link Callable} here since the
* {@link MetricsRetrievalService} doesn't care about when the value returns
* or whether an exception is thrown.
*/
private static final class RESTRunnable extends MetricRunnable {
private final Gson m_gson;
private final Cache<String, Map<String, String>> m_cache;
/**
* Constructor.
*
* @param cache
* @param queuedUrls
* @param ttlUrlCache
* @param gson
* @param streamProvider
* @param restUrl
*/
private RESTRunnable(Cache<String, Map<String, String>> cache, Set<String> queuedUrls,
Cache<String, String> ttlUrlCache, Gson gson, StreamProvider streamProvider,
String restUrl) {
super(streamProvider, restUrl, queuedUrls, ttlUrlCache);
m_cache = cache;
m_gson = gson;
}
/**
* {@inheritDoc}
*/
@Override
protected void processInputStreamAndCacheResult(InputStream inputStream) throws Exception {
Type type = new TypeToken<Map<Object, Object>>() {}.getType();
JsonReader jsonReader = new JsonReader(
new BufferedReader(new InputStreamReader(inputStream)));
Map<String, String> jsonMap = m_gson.fromJson(jsonReader, type);
m_cache.put(m_url, jsonMap);
}
}
/**
* A default exception handler.
*/
private static final class MetricRunnableExceptionHandler implements UncaughtExceptionHandler {
/**
* {@inheritDoc}
*/
@Override
public void uncaughtException(Thread t, Throwable e) {
LOG.error("Asynchronous metric retrieval encountered an exception with thread {}", t, e);
}
}
}
| ambari-server/src/main/java/org/apache/ambari/server/state/services/MetricsRetrievalService.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.ambari.server.state.services;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.ambari.server.AmbariService;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.controller.jmx.JMXMetricHolder;
import org.apache.ambari.server.controller.utilities.ScalingThreadPoolExecutor;
import org.apache.ambari.server.controller.utilities.StreamProvider;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.AbstractService;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.inject.Inject;
/**
* The {@link MetricsRetrievalService} is used as a headless, autonomous service
* which encapsulates:
* <ul>
* <li>An {@link ExecutorService} for fullfilling remote metric URL requests
* <li>A cache for JMX metrics
* <li>A cache for REST metrics
* </ul>
*
* Classes can inject an instance of this service in order to gain access to its
* caches and request mechanism.
* <p/>
* Callers must submit a request to the service in order to reach out and pull
* in remote metric data. Otherwise, the cache will never be populated. On the
* first usage of this service, the cache will always be empty. On every
* subsequent request, the data from the prior invocation of
* {@link #submitRequest(MetricSourceType, StreamProvider, String)} will be available.
* <p/>
* Metric data is cached temporarily and is controlled by
* {@link Configuration#getMetricsServiceCacheTimeout()}.
* <p/>
* In order to control throttling requests to the same endpoint,
* {@link Configuration#isMetricsServiceRequestTTLCacheEnabled()} can be enabled
* to allow for a fixed interval of time to pass between requests.
*/
@AmbariService
public class MetricsRetrievalService extends AbstractService {
/**
* The type of web service hosting the metrics.
*/
public enum MetricSourceType {
/**
* JMX
*/
JMX,
/**
* REST
*/
REST
}
/**
* Logger.
*/
protected final static Logger LOG = LoggerFactory.getLogger(MetricsRetrievalService.class);
/**
* The timeout for exceptions which are caught and then cached to prevent log
* spamming.
*
* @see #s_exceptionCache
*/
private static final int EXCEPTION_CACHE_TIMEOUT_MINUTES = 20;
/**
* Exceptions from this service should not SPAM the logs; so cache exceptions
* and log once every {@vale #EXCEPTION_CACHE_TIMEOUT_MINUTES} minutes.
*/
private static final Cache<String, Throwable> s_exceptionCache = CacheBuilder.newBuilder().expireAfterWrite(
EXCEPTION_CACHE_TIMEOUT_MINUTES, TimeUnit.MINUTES).build();
/**
* Configuration.
*/
@Inject
private Configuration m_configuration;
/**
* Used for reading REST JSON responses.
*/
@Inject
private Gson m_gson;
/**
* A cache of URL to parsed JMX beans
*/
private Cache<String, JMXMetricHolder> m_jmxCache;
/**
* A cache of URL to parsed REST data.
*/
private Cache<String, Map<String, String>> m_restCache;
/**
* The {@link Executor} which will handle all of the requests to load remote
* metrics from URLs.
*/
private ThreadPoolExecutor m_threadPoolExecutor;
/**
* Used to parse remote JMX JSON into a {@link Map}.
*/
private final ObjectReader m_jmxObjectReader;
/**
* A thread-safe collection of all of the URL endpoints queued for processing.
* This helps prevent the same endpoint from being queued multiple times.
*/
private final Set<String> m_queuedUrls = Sets.newConcurrentHashSet();
/**
* An evicting cache which ensures that multiple requests for the same
* endpoint are not executed back-to-back. When enabled, a fixed period of
* time must pass before this service will make requests to a previously
* retrieved endpoint.
* <p/>
* If this cache is not enabled, then it will be {@code null}.
* <p/>
* For simplicity, this is a cache of URL to URL.
*/
private Cache<String, String> m_ttlUrlCache;
/**
* The size of the worker queue (used for logged warnings about size).
*/
private int m_queueMaximumSize;
/**
* Constructor.
*
*/
public MetricsRetrievalService() {
ObjectMapper jmxObjectMapper = new ObjectMapper();
jmxObjectMapper.configure(DeserializationConfig.Feature.USE_ANNOTATIONS, false);
m_jmxObjectReader = jmxObjectMapper.reader(JMXMetricHolder.class);
}
/**
* {@inheritDoc}
*/
@Override
protected void doStart() {
// initialize the caches
int jmxCacheExpirationMinutes = m_configuration.getMetricsServiceCacheTimeout();
m_jmxCache = CacheBuilder.newBuilder().expireAfterWrite(jmxCacheExpirationMinutes,
TimeUnit.MINUTES).build();
m_restCache = CacheBuilder.newBuilder().expireAfterWrite(jmxCacheExpirationMinutes,
TimeUnit.MINUTES).build();
// enable the TTL cache if configured; otherwise leave it as null
int ttlSeconds = m_configuration.getMetricCacheTTLSeconds();
boolean ttlCacheEnabled = m_configuration.isMetricsServiceRequestTTLCacheEnabled();
if (ttlCacheEnabled) {
m_ttlUrlCache = CacheBuilder.newBuilder().expireAfterWrite(ttlSeconds,
TimeUnit.SECONDS).build();
}
// iniitalize the executor service
int corePoolSize = m_configuration.getMetricsServiceThreadPoolCoreSize();
int maxPoolSize = m_configuration.getMetricsServiceThreadPoolMaxSize();
m_queueMaximumSize = m_configuration.getMetricsServiceWorkerQueueSize();
int threadPriority = m_configuration.getMetricsServiceThreadPriority();
m_threadPoolExecutor = new ScalingThreadPoolExecutor(corePoolSize, maxPoolSize, 30,
TimeUnit.SECONDS, m_queueMaximumSize);
m_threadPoolExecutor.allowCoreThreadTimeOut(true);
m_threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(
"ambari-metrics-retrieval-service-thread-%d").setPriority(
threadPriority).setUncaughtExceptionHandler(
new MetricRunnableExceptionHandler()).build();
m_threadPoolExecutor.setThreadFactory(threadFactory);
LOG.info(
"Initializing the Metrics Retrieval Service with core={}, max={}, workerQueue={}, threadPriority={}",
corePoolSize, maxPoolSize, m_queueMaximumSize, threadPriority);
if (ttlCacheEnabled) {
LOG.info("Metrics Retrieval Service request TTL cache is enabled and set to {} seconds",
ttlSeconds);
}
}
/**
* Testing method for setting a synchronous {@link ThreadPoolExecutor}.
*
* @param threadPoolExecutor
*/
public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
m_threadPoolExecutor = threadPoolExecutor;
}
/**
* {@inheritDoc}
*/
@Override
protected void doStop() {
m_jmxCache.invalidateAll();
m_restCache.invalidateAll();
if (null != m_ttlUrlCache) {
m_ttlUrlCache.invalidateAll();
}
m_queuedUrls.clear();
m_threadPoolExecutor.shutdownNow();
}
/**
* Submit a {@link Runnable} for execution which retrieves metric data from
* the supplied endpoint. This will run inside of an {@link ExecutorService}
* to retrieve metric data from a URL endpoint and parse the result into a
* cached value.
* <p/>
* Once metric data is retrieved it is cached. Data in the cache can be
* retrieved via {@link #getCachedJMXMetric(String)} or
* {@link #getCachedRESTMetric(String)}, depending on the type of metric
* requested.
* <p/>
* Callers need not worry about invoking this mulitple times for the same URL
* endpoint. A single endpoint will only be enqueued once regardless of how
* many times this method is called until it has been fully retrieved and
* parsed. If the last endpoint request was too recent, then this method will
* opt to not make another call until the TTL period expires.
*
* @param type
* the type of service hosting the metric (not {@code null}).
* @param streamProvider
* the {@link StreamProvider} to use to read from the remote
* endpoint.
* @param jmxUrl
* the URL to read from
*
* @see #getCachedJMXMetric(String)
*/
public void submitRequest(MetricSourceType type, StreamProvider streamProvider, String url) {
// check to ensure that the request isn't already queued
if (m_queuedUrls.contains(url)) {
return;
}
// check to ensure that the request wasn't made too recently
if (null != m_ttlUrlCache && null != m_ttlUrlCache.getIfPresent(url)) {
return;
}
// log warnings if the queue size seems to be rather large
BlockingQueue<Runnable> queue = m_threadPoolExecutor.getQueue();
int queueSize = queue.size();
if (queueSize > Math.floor(0.9f * m_queueMaximumSize)) {
LOG.warn("The worker queue contains {} work items and is at {}% of capacity", queueSize,
((float) queueSize / m_queueMaximumSize) * 100);
}
// enqueue this URL
m_queuedUrls.add(url);
Runnable runnable = null;
switch (type) {
case JMX:
runnable = new JMXRunnable(m_jmxCache, m_queuedUrls, m_ttlUrlCache, m_jmxObjectReader,
streamProvider, url);
break;
case REST:
runnable = new RESTRunnable(m_restCache, m_queuedUrls, m_ttlUrlCache, m_gson,
streamProvider, url);
break;
default:
LOG.warn("Unable to retrieve metrics for the unknown type {}", type);
break;
}
if (null != runnable) {
m_threadPoolExecutor.execute(runnable);
}
}
/**
* Gets a cached JMX metric in the form of a {@link JMXMetricHolder}. If there
* is no metric data cached for the given URL, then {@code null} is returned.
* <p/>
* The onky way this cache is populated is by requesting the data to be loaded
* asynchronously via
* {@link #submitRequest(MetricSourceType, StreamProvider, String)} with the
* {@link MetricSourceType#JMX} type.
*
* @param jmxUrl
* the URL to retrieve cached data for (not {@code null}).
* @return the metric, or {@code null} if none.
*/
public JMXMetricHolder getCachedJMXMetric(String jmxUrl) {
return m_jmxCache.getIfPresent(jmxUrl);
}
/**
* Gets a cached REST metric in the form of a {@link Map}. If there is no
* metric data cached for the given URL, then {@code null} is returned.
* <p/>
* The onky way this cache is populated is by requesting the data to be loaded
* asynchronously via
* {@link #submitRequest(MetricSourceType, StreamProvider, String)} with the
* {@link MetricSourceType#REST} type.
*
* @param restUrl
* the URL to retrieve cached data for (not {@code null}).
* @return the metric, or {@code null} if none.
*/
public Map<String, String> getCachedRESTMetric(String restUrl) {
return m_restCache.getIfPresent(restUrl);
}
/**
* Encapsulates the common logic for all metric {@link Runnable} instnaces.
*/
private static abstract class MetricRunnable implements Runnable {
/**
* An initialized stream provider to read the remote endpoint.
*/
protected final StreamProvider m_streamProvider;
/**
* A fully-qualified URL to read from.
*/
protected final String m_url;
/**
* The URLs which have been requested but not yet read.
*/
private final Set<String> m_queuedUrls;
/**
* An evicting cache used to control whether a request for a metric can be
* made or if it is too soon after the last request.
*/
private final Cache<String, String> m_ttlUrlCache;
/**
* Constructor.
*
* @param streamProvider
* the stream provider to read the URL with
* @param url
* the URL endpoint to read data from (JMX or REST)
* @param queuedUrls
* the URLs which are currently waiting to be processed. This
* method will remove the specified URL from this {@link Set} when
* it completes (successful or not).
* @param m_ttlUrlCache
* an evicting cache which is used to determine if a request for a
* metric is too soon after the last request, or {@code null} if
* requests can be made sequentially without any separation.
*/
private MetricRunnable(StreamProvider streamProvider, String url, Set<String> queuedUrls,
Cache<String, String> ttlUrlCache) {
m_streamProvider = streamProvider;
m_url = url;
m_queuedUrls = queuedUrls;
m_ttlUrlCache = ttlUrlCache;
}
/**
* {@inheritDoc}
*/
@Override
public final void run() {
// provide some profiling
long startTime = 0;
long endTime = 0;
boolean isDebugEnabled = LOG.isDebugEnabled();
if (isDebugEnabled) {
startTime = System.currentTimeMillis();
}
InputStream inputStream = null;
try {
if (isDebugEnabled) {
endTime = System.currentTimeMillis();
LOG.debug("Loading metric JSON from {} took {}ms", m_url, (endTime - startTime));
}
// read the stream and process it
inputStream = m_streamProvider.readFrom(m_url);
processInputStreamAndCacheResult(inputStream);
// cache the URL, but only after successful parsing of the response
if (null != m_ttlUrlCache) {
m_ttlUrlCache.put(m_url, m_url);
}
} catch (Exception exception) {
logException(exception, m_url);
} finally {
IOUtils.closeQuietly(inputStream);
// remove this URL from the list of queued URLs to ensure it will be
// requested again
m_queuedUrls.remove(m_url);
}
}
/**
* Reads data from the specified {@link InputStream} and processes that into
* a cachable value. The value will then be cached by this method.
*
* @param inputStream
* @throws Exception
*/
protected abstract void processInputStreamAndCacheResult(InputStream inputStream)
throws Exception;
/**
* Logs the exception for the URL exactly once and caches the fact that the
* exception was logged. This is to prevent an endpoint being down from
* spamming the logs.
*
* @param throwable
* the exception to log (not {@code null}).
* @param url
* the URL associated with the exception (not {@code null}).
*/
final void logException(Throwable throwable, String url) {
String cacheKey = buildCacheKey(throwable, url);
if (null == s_exceptionCache.getIfPresent(cacheKey)) {
// cache it and log it
s_exceptionCache.put(cacheKey, throwable);
LOG.error(
"Unable to retrieve metrics from {}. Subsequent failures will be suppressed from the log for {} minutes.",
url, EXCEPTION_CACHE_TIMEOUT_MINUTES, throwable);
}
}
/**
* Builds a unique cache key for the combination of {@link Throwable} and
* {@link String} URL.
*
* @param throwable
* @param url
* @return the key, such as {@value IOException-http://www.server.com/jmx}.
*/
private String buildCacheKey(Throwable throwable, String url) {
if (null == throwable || null == url) {
return "";
}
String throwableName = throwable.getClass().getSimpleName();
return throwableName + "-" + url;
}
}
/**
* A {@link Runnable} used to retrieve JMX data from a remote URL endpoint.
* There is no need for a {@link Callable} here since the
* {@link MetricsRetrievalService} doesn't care about when the value returns or
* whether an exception is thrown.
*/
private static final class JMXRunnable extends MetricRunnable {
private final ObjectReader m_jmxObjectReader;
private final Cache<String, JMXMetricHolder> m_cache;
/**
* Constructor.
*
* @param cache
* @param queuedUrls
* @param ttlUrlCache
* @param jmxObjectReader
* @param streamProvider
* @param jmxUrl
*/
private JMXRunnable(Cache<String, JMXMetricHolder> cache, Set<String> queuedUrls,
Cache<String, String> ttlUrlCache, ObjectReader jmxObjectReader,
StreamProvider streamProvider, String jmxUrl) {
super(streamProvider, jmxUrl, queuedUrls, ttlUrlCache);
m_cache = cache;
m_jmxObjectReader = jmxObjectReader;
}
/**
* {@inheritDoc}
*/
@Override
protected void processInputStreamAndCacheResult(InputStream inputStream) throws Exception {
JMXMetricHolder jmxMetricHolder = m_jmxObjectReader.readValue(inputStream);
m_cache.put(m_url, jmxMetricHolder);
}
}
/**
* A {@link Runnable} used to retrieve REST data from a remote URL endpoint.
* There is no need for a {@link Callable} here since the
* {@link MetricsRetrievalService} doesn't care about when the value returns
* or whether an exception is thrown.
*/
private static final class RESTRunnable extends MetricRunnable {
private final Gson m_gson;
private final Cache<String, Map<String, String>> m_cache;
/**
* Constructor.
*
* @param cache
* @param queuedUrls
* @param ttlUrlCache
* @param gson
* @param streamProvider
* @param restUrl
*/
private RESTRunnable(Cache<String, Map<String, String>> cache, Set<String> queuedUrls,
Cache<String, String> ttlUrlCache, Gson gson, StreamProvider streamProvider,
String restUrl) {
super(streamProvider, restUrl, queuedUrls, ttlUrlCache);
m_cache = cache;
m_gson = gson;
}
/**
* {@inheritDoc}
*/
@Override
protected void processInputStreamAndCacheResult(InputStream inputStream) throws Exception {
Type type = new TypeToken<Map<Object, Object>>() {}.getType();
JsonReader jsonReader = new JsonReader(
new BufferedReader(new InputStreamReader(inputStream)));
Map<String, String> jsonMap = m_gson.fromJson(jsonReader, type);
m_cache.put(m_url, jsonMap);
}
}
/**
* A default exception handler.
*/
private static final class MetricRunnableExceptionHandler implements UncaughtExceptionHandler {
/**
* {@inheritDoc}
*/
@Override
public void uncaughtException(Thread t, Throwable e) {
LOG.error("Asynchronous metric retrieval encountered an exception with thread {}", t, e);
}
}
}
| AMBARI-18331 - JMX metric retrieval method may unnecessarily refresh metrics at a high rate (part2) (jonathanhurley)
| ambari-server/src/main/java/org/apache/ambari/server/state/services/MetricsRetrievalService.java | AMBARI-18331 - JMX metric retrieval method may unnecessarily refresh metrics at a high rate (part2) (jonathanhurley) | <ide><path>mbari-server/src/main/java/org/apache/ambari/server/state/services/MetricsRetrievalService.java
<ide> TimeUnit.MINUTES).build();
<ide>
<ide> // enable the TTL cache if configured; otherwise leave it as null
<del> int ttlSeconds = m_configuration.getMetricCacheTTLSeconds();
<add> int ttlSeconds = m_configuration.getMetricsServiceRequestTTL();
<ide> boolean ttlCacheEnabled = m_configuration.isMetricsServiceRequestTTLCacheEnabled();
<ide> if (ttlCacheEnabled) {
<ide> m_ttlUrlCache = CacheBuilder.newBuilder().expireAfterWrite(ttlSeconds, |
|
Java | mit | cd70356abe578a369b3cb639358ea84428a17c39 | 0 | AncientMariner/ChessBoard,AncientMariner/ChessBoard | package org.xander.chessboard;
import org.junit.Ignore;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.xander.chessboard.figures.Figure.BISHOP;
import static org.xander.chessboard.figures.Figure.KING;
import static org.xander.chessboard.figures.Figure.KNIGHT;
import static org.xander.chessboard.figures.Figure.QUEEN;
import static org.xander.chessboard.figures.Figure.ROOK;
import static org.xander.chessboard.figuresPlacement.FiguresTestUtil.leftOnlyFigures;
public class ChessboardTest {
public static final int DIMENSION_6 = 6;
@Test
public void chessBoardBasic() {
HashMap<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(ROOK.toString(), 1);
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(DIMENSION_6).build();
assertNotNull(chessboard);
assertEquals(DIMENSION_6, chessboard.getDimension());
}
@Test(expected = IllegalStateException.class)
public void chessBoardBasicNegative() {
Chessboard.newBuilder(null).withDimension(DIMENSION_6).build();
}
@Test(expected = IllegalStateException.class)
public void nonExistingFigures() {
HashMap<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put("a", 1);
Chessboard.newBuilder(figureQuantityMap).build().placeFiguresOnBoard(" ");
}
@Test(expected = IllegalStateException.class)
public void nonExistingFigure() {
HashMap<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put("PAWN", 1);
Chessboard.newBuilder(figureQuantityMap).build().placeFiguresOnBoard("......");
}
@Test(expected = IllegalStateException.class)
public void moreThanExpectedFigures() {
HashMap<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(QUEEN.toString(), 3);
figureQuantityMap.put(BISHOP.toString(), 4);
figureQuantityMap.put(ROOK.toString(), 5);
figureQuantityMap.put(KNIGHT.toString(), 6);
figureQuantityMap.put("PAWN", 8);
Chessboard.newBuilder(figureQuantityMap).withKing().withQueen().withBishop().withRook().withKnight().build();
}
@Test(expected = IllegalStateException.class)
public void notDesiredFiguresWithPawn() {
HashMap<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(QUEEN.toString(), 3);
figureQuantityMap.put(BISHOP.toString(), 4);
figureQuantityMap.put(KNIGHT.toString(), 6);
figureQuantityMap.put("PAWN", 8);
Chessboard.newBuilder(figureQuantityMap).withKing().withQueen().withBishop().withRook().withKnight().build();
}
@Test
public void chessBoardFigures() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(QUEEN.toString(), 3);
figureQuantityMap.put(BISHOP.toString(), 4);
figureQuantityMap.put(ROOK.toString(), 5);
figureQuantityMap.put(KNIGHT.toString(), 6);
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withKing().withQueen().withBishop().withRook().withKnight().build();
assertTrue(figureQuantityMap.equals(chessboard.getFigureQuantityMap()));
}
// runs too long, for now ignored
@Ignore
@Test
public void placeFiguresOnBoard() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(QUEEN.toString(), 3);
figureQuantityMap.put(BISHOP.toString(), 4);
figureQuantityMap.put(ROOK.toString(), 5);
figureQuantityMap.put(KNIGHT.toString(), 6);
int dimension = 8;
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(dimension).withKing().withQueen().withBishop().withRook().withKnight().build();
Set<String> boards = chessboard.placeFiguresOnBoard(chessboard.drawEmptyBoard());
assertThat("more than 1 figure is present",
boards.contains("kxkxqxxx\n" +
"xxxxxxqx\n" +
"qxxxxxxx\n" +
"xxbbxbxx\n" +
"xxxxxbxr\n" +
"xxxxxxxx\n" +
"xxxxxxxx\n" +
"xxxrxxxx\n"), is(true));
}
//currently out of memory error, requires optimization
@Ignore
@Test
public void readmeRequirement() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(QUEEN.toString(), 2);
figureQuantityMap.put(BISHOP.toString(), 2);
figureQuantityMap.put(KNIGHT.toString(), 1);
int dimension = 7;
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(dimension).withKing().withQueen().withBishop().withKnight().build();
Set<String> boards = chessboard.placeFiguresOnBoard(chessboard.drawEmptyBoard());
System.out.println();
}
@Test(expected = IllegalStateException.class)
public void placeALotOfFiguresOnBoard() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 22);
figureQuantityMap.put(QUEEN.toString(), 23);
figureQuantityMap.put(BISHOP.toString(), 24);
figureQuantityMap.put(ROOK.toString(), 25);
figureQuantityMap.put(KNIGHT.toString(), 26);
int dimension = 8;
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(dimension).withKing().withQueen().withBishop().withRook().withKnight().build();
chessboard.placeFiguresOnBoard(chessboard.drawEmptyBoard());
}
@Test(expected = IllegalStateException.class)
public void placeAFigureOnBoardNegative() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withKing().build();
chessboard.placeFiguresOnBoard("");
}
@Test
public void multipleFigures2() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(ROOK.toString(), 2);
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(8).withKing().withRook().build();
Set<String> boards = chessboard.placeFiguresOnBoard(chessboard.drawEmptyBoard());
assertThat("there is no boards", boards.size() > 0, is(true));
for (String board : boards) {
assertTrue("all elements are not present on each board", board.contains("k") && board.contains("r") && !board.contains("b"));
assertTrue("all elements are not present on each board", leftOnlyFigures(board).length() == 4);
}
}
@Test
public void multipleFigures3() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(ROOK.toString(), 2);
figureQuantityMap.put(KNIGHT.toString(), 2);
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(5).withKing().withRook().withKnight().build();
Set<String> boards = chessboard.placeFiguresOnBoard(chessboard.drawEmptyBoard());
assertThat("there is no boards", boards.size() > 0, is(true));
for (String board : boards) {
assertTrue("all elements are not present on each board", board.contains("k") && board.contains("r") && board.contains("n"));
assertTrue("all elements are not present on each board", leftOnlyFigures(board).length() == 6);
}
}
//todo check such a situation
@Test
public void multipleFigures1() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(BISHOP.toString(), 2);
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(6).withBishop().build();
Set<String> boards = chessboard.placeFiguresOnBoard("bbbbbb\n" +
"b....b\n" +
"b....b\n" +
"b....b\n" +
"b....b\n" +
"bbbbbb\n");
assertThat("there is no boards", boards.size() > 0, is(true));
for (String board : boards) {
assertTrue("all elements are not present on each board", board.contains("b") && !board.contains("r") && !board.contains("k"));
assertTrue("all elements are not present on each board", leftOnlyFigures(board).length() == 21);
}
}
@Test
public void smallBoard() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 1);
figureQuantityMap.put(QUEEN.toString(), 1);
int dimension = 2;
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(dimension).withKing().withQueen().withBishop().withRook().withKnight().build();
Set<String> boards = chessboard.placeFiguresOnBoard(chessboard.drawEmptyBoard());
assertThat("more than 1 figure is present",
boards.contains("kx\n" + "xx\n"), is(true));
}
//todo check for board figures legal placement before calculation
}
| src/test/java/org/xander/chessboard/ChessboardTest.java | package org.xander.chessboard;
import org.junit.Ignore;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.xander.chessboard.figures.Figure.BISHOP;
import static org.xander.chessboard.figures.Figure.KING;
import static org.xander.chessboard.figures.Figure.KNIGHT;
import static org.xander.chessboard.figures.Figure.QUEEN;
import static org.xander.chessboard.figures.Figure.ROOK;
import static org.xander.chessboard.figuresPlacement.FiguresTestUtil.leftOnlyFigures;
public class ChessboardTest {
public static final int DIMENSION_6 = 6;
@Test
public void chessBoardBasic() {
HashMap<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(ROOK.toString(), 1);
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(DIMENSION_6).build();
assertNotNull(chessboard);
assertEquals(DIMENSION_6, chessboard.getDimension());
}
@Test(expected = IllegalStateException.class)
public void chessBoardBasicNegative() {
Chessboard.newBuilder(null).withDimension(DIMENSION_6).build();
}
@Test(expected = IllegalStateException.class)
public void nonExistingFigures() {
HashMap<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put("a", 1);
Chessboard.newBuilder(figureQuantityMap).build().placeFiguresOnBoard(" ");
}
@Test(expected = IllegalStateException.class)
public void nonExistingFigure() {
HashMap<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put("PAWN", 1);
Chessboard.newBuilder(figureQuantityMap).build().placeFiguresOnBoard("......");
}
@Test(expected = IllegalStateException.class)
public void moreThanExpectedFigures() {
HashMap<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(QUEEN.toString(), 3);
figureQuantityMap.put(BISHOP.toString(), 4);
figureQuantityMap.put(ROOK.toString(), 5);
figureQuantityMap.put(KNIGHT.toString(), 6);
figureQuantityMap.put("PAWN", 8);
Chessboard.newBuilder(figureQuantityMap).withKing().withQueen().withBishop().withRook().withKnight().build();
}
@Test(expected = IllegalStateException.class)
public void notDesiredFiguresWithPawn() {
HashMap<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(QUEEN.toString(), 3);
figureQuantityMap.put(BISHOP.toString(), 4);
figureQuantityMap.put(KNIGHT.toString(), 6);
figureQuantityMap.put("PAWN", 8);
Chessboard.newBuilder(figureQuantityMap).withKing().withQueen().withBishop().withRook().withKnight().build();
}
@Test
public void chessBoardFigures() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(QUEEN.toString(), 3);
figureQuantityMap.put(BISHOP.toString(), 4);
figureQuantityMap.put(ROOK.toString(), 5);
figureQuantityMap.put(KNIGHT.toString(), 6);
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withKing().withQueen().withBishop().withRook().withKnight().build();
assertTrue(figureQuantityMap.equals(chessboard.getFigureQuantityMap()));
}
// runs too long, for now ignored
@Ignore
@Test
public void placeFiguresOnBoard() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(QUEEN.toString(), 3);
figureQuantityMap.put(BISHOP.toString(), 4);
figureQuantityMap.put(ROOK.toString(), 5);
figureQuantityMap.put(KNIGHT.toString(), 6);
int dimension = 8;
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(dimension).withKing().withQueen().withBishop().withRook().withKnight().build();
Set<String> boards = chessboard.placeFiguresOnBoard(chessboard.drawEmptyBoard());
assertThat("more than 1 figure is present",
boards.contains("kxkxqxxx\n" +
"xxxxxxqx\n" +
"qxxxxxxx\n" +
"xxbbxbxx\n" +
"xxxxxbxr\n" +
"xxxxxxxx\n" +
"xxxxxxxx\n" +
"xxxrxxxx\n"), is(true));
}
//currently out of memory error, requires optimization
@Ignore
@Test
public void readmeRequirement() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(QUEEN.toString(), 2);
figureQuantityMap.put(BISHOP.toString(), 2);
figureQuantityMap.put(KNIGHT.toString(), 1);
int dimension = 7;
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(dimension).withKing().withQueen().withBishop().withKnight().build();
Set<String> boards = chessboard.placeFiguresOnBoard(chessboard.drawEmptyBoard());
System.out.println();
}
@Test(expected = IllegalStateException.class)
public void placeALotOfFiguresOnBoard() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 22);
figureQuantityMap.put(QUEEN.toString(), 23);
figureQuantityMap.put(BISHOP.toString(), 24);
figureQuantityMap.put(ROOK.toString(), 25);
figureQuantityMap.put(KNIGHT.toString(), 26);
int dimension = 8;
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(dimension).withKing().withQueen().withBishop().withRook().withKnight().build();
chessboard.placeFiguresOnBoard(chessboard.drawEmptyBoard());
}
@Test(expected = IllegalStateException.class)
public void placeAFigureOnBoardNegative() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withKing().build();
chessboard.placeFiguresOnBoard("");
}
@Test
public void multipleFigures2() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(ROOK.toString(), 2);
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(8).withKing().withRook().build();
Set<String> boards = chessboard.placeFiguresOnBoard(chessboard.drawEmptyBoard());
assertThat("there is no boards", boards.size() > 0, is(true));
for (String board : boards) {
assertTrue("all elements are not present on each board", board.contains("k") && board.contains("r") && !board.contains("b"));
assertTrue("all elements are not present on each board", leftOnlyFigures(board).length() == 4);
}
}
@Test
public void multipleFigures3() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(KING.toString(), 2);
figureQuantityMap.put(ROOK.toString(), 2);
figureQuantityMap.put(KNIGHT.toString(), 2);
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(5).withKing().withRook().withKnight().build();
Set<String> boards = chessboard.placeFiguresOnBoard(chessboard.drawEmptyBoard());
assertThat("there is no boards", boards.size() > 0, is(true));
for (String board : boards) {
assertTrue("all elements are not present on each board", board.contains("k") && board.contains("r") && board.contains("n"));
assertTrue("all elements are not present on each board", leftOnlyFigures(board).length() == 6);
}
}
//todo check such a situation
@Test
public void multipleFigures1() {
Map<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(BISHOP.toString(), 2);
Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(6).withBishop().build();
Set<String> boards = chessboard.placeFiguresOnBoard("bbbbbb\n" +
"b....b\n" +
"b....b\n" +
"b....b\n" +
"b....b\n" +
"bbbbbb\n");
assertThat("there is no boards", boards.size() > 0, is(true));
for (String board : boards) {
assertTrue("all elements are not present on each board", board.contains("b") && !board.contains("r") && !board.contains("k"));
assertTrue("all elements are not present on each board", leftOnlyFigures(board).length() == 21);
}
}
//todo check for board figures legal placement before calculation
//todo create test with small board
}
| small board test
| src/test/java/org/xander/chessboard/ChessboardTest.java | small board test | <ide><path>rc/test/java/org/xander/chessboard/ChessboardTest.java
<ide> }
<ide> }
<ide>
<add> @Test
<add> public void smallBoard() {
<add> Map<String, Integer> figureQuantityMap = new HashMap<>();
<add> figureQuantityMap.put(KING.toString(), 1);
<add> figureQuantityMap.put(QUEEN.toString(), 1);
<add>
<add> int dimension = 2;
<add> Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(dimension).withKing().withQueen().withBishop().withRook().withKnight().build();
<add>
<add> Set<String> boards = chessboard.placeFiguresOnBoard(chessboard.drawEmptyBoard());
<add> assertThat("more than 1 figure is present",
<add> boards.contains("kx\n" + "xx\n"), is(true));
<add>
<add> }
<ide> //todo check for board figures legal placement before calculation
<del> //todo create test with small board
<add>
<ide> } |
|
Java | epl-1.0 | 99317b8d4a47ce3ed24303353acde0175f52ea5b | 0 | lttng/lttng-scope,lttng/lttng-scope,lttng/lttng-scope,alexmonthy/lttng-scope,lttng/lttng-scope,alexmonthy/lttng-scope,alexmonthy/lttng-scope | /*******************************************************************************
* Copyright (c) 2012, 2014 Ericsson
*
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Patrick Tasse - Initial API and implementation
* Bernd Hufmann - Added call site and model URI properties
*******************************************************************************/
package org.eclipse.tracecompass.tmf.ui.viewers.events;
import static org.lttng.scope.common.core.NonNullUtils.nullToEmptyString;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.tracecompass.tmf.core.event.ITmfCustomAttributes;
import org.eclipse.tracecompass.tmf.core.event.ITmfEvent;
import org.eclipse.tracecompass.tmf.core.event.ITmfEventField;
import org.eclipse.tracecompass.tmf.core.event.aspect.ITmfEventAspect;
import org.eclipse.tracecompass.tmf.core.event.aspect.TmfBaseAspects;
import org.eclipse.tracecompass.tmf.core.event.lookup.ITmfCallsite;
import org.eclipse.tracecompass.tmf.core.event.lookup.ITmfModelLookup;
import org.eclipse.tracecompass.tmf.core.event.lookup.ITmfSourceLookup;
import org.eclipse.tracecompass.tmf.ui.properties.ReadOnlyTextPropertyDescriptor;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import org.eclipse.ui.views.properties.IPropertySource;
import org.lttng.scope.common.core.StreamUtils;
/**
* Property source for events
*/
public class TmfEventPropertySource implements IPropertySource {
private static final String ID_CONTENT = "event_content"; //$NON-NLS-1$
private static final String ID_SOURCE_LOOKUP = "event_lookup"; //$NON-NLS-1$
private static final String ID_MODEL_URI = "model_uri"; //$NON-NLS-1$
private static final String ID_CUSTOM_ATTRIBUTE = "custom_attribute"; //$NON-NLS-1$
private static final String NAME_CONTENT = "Content"; //$NON-NLS-1$
private static final String NAME_SOURCE_LOOKUP = "Source Lookup"; //$NON-NLS-1$
private static final String NAME_MODEL_URI = "Model URI"; //$NON-NLS-1$
private static final String NAME_CUSTOM_ATTRIBUTES = "Custom Attributes"; //$NON-NLS-1$
private static final String EMPTY_STRING = ""; //$NON-NLS-1$
private final @NonNull ITmfEvent fEvent;
private static class ContentPropertySource implements IPropertySource {
private ITmfEventField fContent;
public ContentPropertySource(ITmfEventField content) {
fContent = content;
}
@Override
public Object getEditableValue() {
return fContent.toString();
}
@Override
public IPropertyDescriptor[] getPropertyDescriptors() {
List<IPropertyDescriptor> descriptors = new ArrayList<>(fContent.getFields().size());
for (ITmfEventField field : fContent.getFields()) {
if (field != null) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(field, field.getName()));
}
}
return descriptors.toArray(new IPropertyDescriptor[0]);
}
@Override
public Object getPropertyValue(Object id) {
ITmfEventField field = (ITmfEventField) id;
if (!field.getFields().isEmpty()) {
return new ContentPropertySource(field);
}
return field.getFormattedValue();
}
@Override
public boolean isPropertySet(Object id) {
return false;
}
@Override
public void resetPropertyValue(Object id) {
}
@Override
public void setPropertyValue(Object id, Object value) {
}
}
private static class SourceLookupPropertySource implements IPropertySource {
private static final String ID_FILE_NAME = "callsite_file"; //$NON-NLS-1$
private static final String ID_LINE_NUMBER = "callsite_line"; //$NON-NLS-1$
private static final String NAME_FILE_NAME = "File"; //$NON-NLS-1$
private static final String NAME_LINE_NUMBER = "Line"; //$NON-NLS-1$
private final ITmfSourceLookup fSourceLookup;
public SourceLookupPropertySource(ITmfSourceLookup lookup) {
fSourceLookup = lookup;
}
@Override
public Object getEditableValue() {
ITmfCallsite cs = fSourceLookup.getCallsite();
if (cs != null) {
return cs.toString();
}
return null;
}
@Override
public IPropertyDescriptor[] getPropertyDescriptors() {
List<IPropertyDescriptor> descriptors= new ArrayList<>();
ITmfCallsite cs = fSourceLookup.getCallsite();
if (cs != null) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_FILE_NAME, NAME_FILE_NAME));
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_LINE_NUMBER, NAME_LINE_NUMBER));
}
return descriptors.toArray(new IPropertyDescriptor[0]);
}
@Override
public String getPropertyValue(Object id) {
ITmfCallsite cs = fSourceLookup.getCallsite();
if (cs == null) {
/*
* The callsite should not be null here, we would not have
* created the descriptors otherwise
*/
throw new IllegalStateException();
}
if (!(id instanceof String)) {
return null;
}
switch ((String) id) {
case ID_FILE_NAME:
return cs.getFileName();
case ID_LINE_NUMBER:
return nullToEmptyString(cs.getLineNo());
default:
return null;
}
}
@Override
public boolean isPropertySet(Object id) {
return false;
}
@Override
public void resetPropertyValue(Object id) {
}
@Override
public void setPropertyValue(Object id, Object value) {
}
}
private class CustomAttributePropertySource implements IPropertySource {
private final ITmfCustomAttributes event;
public CustomAttributePropertySource(ITmfCustomAttributes event) {
this.event = event;
}
@Override
public Object getEditableValue() {
return EMPTY_STRING;
}
@Override
public IPropertyDescriptor[] getPropertyDescriptors() {
List<IPropertyDescriptor> descriptors = new ArrayList<>();
for (String customAttribute : event.listCustomAttributes()) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(customAttribute, customAttribute));
}
return descriptors.toArray(new IPropertyDescriptor[0]);
}
@Override
public Object getPropertyValue(Object id) {
if (!(id instanceof String)) {
return null;
}
return event.getCustomAttribute((String) id);
}
@Override
public boolean isPropertySet(Object id) {
return false;
}
@Override
public void resetPropertyValue(Object id) {
}
@Override
public void setPropertyValue(Object id, Object value) {
}
}
/**
* Default constructor
*
* @param event the event
*/
public TmfEventPropertySource(@NonNull ITmfEvent event) {
super();
this.fEvent = event;
}
@Override
public Object getEditableValue() {
return null;
}
@Override
public IPropertyDescriptor[] getPropertyDescriptors() {
List<IPropertyDescriptor> descriptors= new ArrayList<>();
/* Display properties for event aspects */
getTraceAspects().forEach(aspect -> {
/*
* Contents has its special property source, which puts the fields
* in a sub-tree.
*/
if (aspect == TmfBaseAspects.getContentsAspect()) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CONTENT, NAME_CONTENT));
} else {
String name = aspect.getName();
descriptors.add(new ReadOnlyTextPropertyDescriptor(name, name));
}
});
/* Display source lookup information, if the event supplies it */
if ((fEvent instanceof ITmfSourceLookup) && (((ITmfSourceLookup)fEvent).getCallsite() != null)) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_SOURCE_LOOKUP, NAME_SOURCE_LOOKUP));
}
/* Display Model URI information, if the event supplies it */
if ((fEvent instanceof ITmfModelLookup) && (((ITmfModelLookup) fEvent).getModelUri() != null)) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_MODEL_URI, NAME_MODEL_URI));
}
/* Display custom attributes, if available */
if (fEvent instanceof ITmfCustomAttributes) {
ITmfCustomAttributes event = (ITmfCustomAttributes) fEvent;
if (!event.listCustomAttributes().isEmpty()) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CUSTOM_ATTRIBUTE, NAME_CUSTOM_ATTRIBUTES));
}
}
return descriptors.toArray(new IPropertyDescriptor[0]);
}
@Override
public Object getPropertyValue(Object objectId) {
if (!(objectId instanceof String)) {
return null;
}
String id = (String) objectId;
if (id.equals(ID_MODEL_URI)) {
return ((ITmfModelLookup)fEvent).getModelUri();
} else if (id.equals(ID_SOURCE_LOOKUP)) {
return new SourceLookupPropertySource(((ITmfSourceLookup)fEvent));
} else if (id.equals(ID_CONTENT) && fEvent.getContent() != null) {
return new ContentPropertySource(fEvent.getContent());
} else if (id.equals(ID_CUSTOM_ATTRIBUTE)) {
return new CustomAttributePropertySource((ITmfCustomAttributes) fEvent);
}
/* Look for the ID in the aspect names */
Optional<ITmfEventAspect<?>> potentialAspect = getTraceAspects()
.filter(aspect -> aspect.getName().equals(id))
.findFirst();
if (potentialAspect.isPresent()) {
Object res = potentialAspect.get().resolve(fEvent);
return (res == null ? "" : res.toString()); //$NON-NLS-1$
}
return null;
}
private Stream<ITmfEventAspect<?>> getTraceAspects() {
return StreamUtils.getStream(fEvent.getTrace().getEventAspects());
}
@Override
public boolean isPropertySet(Object id) {
return false;
}
@Override
public void resetPropertyValue(Object id) {
}
@Override
public void setPropertyValue(Object id, Object value) {
}
}
| tmf/org.eclipse.tracecompass.tmf.ui/src/org/eclipse/tracecompass/tmf/ui/viewers/events/TmfEventPropertySource.java | /*******************************************************************************
* Copyright (c) 2012, 2014 Ericsson
*
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Patrick Tasse - Initial API and implementation
* Bernd Hufmann - Added call site and model URI properties
*******************************************************************************/
package org.eclipse.tracecompass.tmf.ui.viewers.events;
import static org.lttng.scope.common.core.NonNullUtils.nullToEmptyString;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.tracecompass.tmf.core.event.ITmfCustomAttributes;
import org.eclipse.tracecompass.tmf.core.event.ITmfEvent;
import org.eclipse.tracecompass.tmf.core.event.ITmfEventField;
import org.eclipse.tracecompass.tmf.core.event.lookup.ITmfCallsite;
import org.eclipse.tracecompass.tmf.core.event.lookup.ITmfModelLookup;
import org.eclipse.tracecompass.tmf.core.event.lookup.ITmfSourceLookup;
import org.eclipse.tracecompass.tmf.core.timestamp.ITmfTimestamp;
import org.eclipse.tracecompass.tmf.ui.properties.ReadOnlyTextPropertyDescriptor;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import org.eclipse.ui.views.properties.IPropertySource;
/**
* Property source for events
*/
public class TmfEventPropertySource implements IPropertySource {
private static final String ID_TIMESTAMP = "event_timestamp"; //$NON-NLS-1$
private static final String ID_TYPE = "event_type"; //$NON-NLS-1$
private static final String ID_TRACE = "trace_attribute"; //$NON-NLS-1$
private static final String ID_CONTENT = "event_content"; //$NON-NLS-1$
private static final String ID_SOURCE_LOOKUP = "event_lookup"; //$NON-NLS-1$
private static final String ID_MODEL_URI = "model_uri"; //$NON-NLS-1$
private static final String ID_CUSTOM_ATTRIBUTE = "custom_attribute"; //$NON-NLS-1$
private static final String NAME_TIMESTAMP = "Timestamp"; //$NON-NLS-1$
private static final String NAME_TYPE = "Type"; //$NON-NLS-1$
private static final String NAME_TRACE = "Trace"; //$NON-NLS-1$
private static final String NAME_CONTENT = "Content"; //$NON-NLS-1$
private static final String NAME_SOURCE_LOOKUP = "Source Lookup"; //$NON-NLS-1$
private static final String NAME_MODEL_URI = "Model URI"; //$NON-NLS-1$
private static final String NAME_CUSTOM_ATTRIBUTES = "Custom Attributes"; //$NON-NLS-1$
private static final String EMPTY_STRING = ""; //$NON-NLS-1$
private ITmfEvent fEvent;
private static class TimestampPropertySource implements IPropertySource {
private static final String ID_TIMESTAMP_VALUE = "timestamp_value"; //$NON-NLS-1$
private static final String ID_TIMESTAMP_SCALE = "timestamp_scale"; //$NON-NLS-1$
private static final String NAME_TIMESTAMP_VALUE = "value"; //$NON-NLS-1$
private static final String NAME_TIMESTAMP_SCALE = "scale"; //$NON-NLS-1$
private ITmfTimestamp fTimestamp;
public TimestampPropertySource(ITmfTimestamp timestamp) {
fTimestamp = timestamp;
}
@Override
public Object getEditableValue() {
return fTimestamp.toString();
}
@Override
public IPropertyDescriptor[] getPropertyDescriptors() {
IPropertyDescriptor[] descriptors = new IPropertyDescriptor[2];
descriptors[0] = new ReadOnlyTextPropertyDescriptor(ID_TIMESTAMP_VALUE, NAME_TIMESTAMP_VALUE);
descriptors[1] = new ReadOnlyTextPropertyDescriptor(ID_TIMESTAMP_SCALE, NAME_TIMESTAMP_SCALE);
return descriptors;
}
@Override
public Object getPropertyValue(Object id) {
if (id.equals(ID_TIMESTAMP_VALUE)) {
return Long.toString(fTimestamp.getValue());
} else if (id.equals(ID_TIMESTAMP_SCALE)) {
return Integer.toString(fTimestamp.getScale());
}
return null;
}
@Override
public boolean isPropertySet(Object id) {
return false;
}
@Override
public void resetPropertyValue(Object id) {
}
@Override
public void setPropertyValue(Object id, Object value) {
}
}
private static class ContentPropertySource implements IPropertySource {
private ITmfEventField fContent;
public ContentPropertySource(ITmfEventField content) {
fContent = content;
}
@Override
public Object getEditableValue() {
return fContent.toString();
}
@Override
public IPropertyDescriptor[] getPropertyDescriptors() {
List<IPropertyDescriptor> descriptors = new ArrayList<>(fContent.getFields().size());
for (ITmfEventField field : fContent.getFields()) {
if (field != null) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(field, field.getName()));
}
}
return descriptors.toArray(new IPropertyDescriptor[0]);
}
@Override
public Object getPropertyValue(Object id) {
ITmfEventField field = (ITmfEventField) id;
if (!field.getFields().isEmpty()) {
return new ContentPropertySource(field);
}
return field.getFormattedValue();
}
@Override
public boolean isPropertySet(Object id) {
return false;
}
@Override
public void resetPropertyValue(Object id) {
}
@Override
public void setPropertyValue(Object id, Object value) {
}
}
private static class SourceLookupPropertySource implements IPropertySource {
private static final String ID_FILE_NAME = "callsite_file"; //$NON-NLS-1$
private static final String ID_LINE_NUMBER = "callsite_line"; //$NON-NLS-1$
private static final String NAME_FILE_NAME = "File"; //$NON-NLS-1$
private static final String NAME_LINE_NUMBER = "Line"; //$NON-NLS-1$
private final ITmfSourceLookup fSourceLookup;
public SourceLookupPropertySource(ITmfSourceLookup lookup) {
fSourceLookup = lookup;
}
@Override
public Object getEditableValue() {
ITmfCallsite cs = fSourceLookup.getCallsite();
if (cs != null) {
return cs.toString();
}
return null;
}
@Override
public IPropertyDescriptor[] getPropertyDescriptors() {
List<IPropertyDescriptor> descriptors= new ArrayList<>();
ITmfCallsite cs = fSourceLookup.getCallsite();
if (cs != null) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_FILE_NAME, NAME_FILE_NAME));
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_LINE_NUMBER, NAME_LINE_NUMBER));
}
return descriptors.toArray(new IPropertyDescriptor[0]);
}
@Override
public String getPropertyValue(Object id) {
ITmfCallsite cs = fSourceLookup.getCallsite();
if (cs == null) {
/*
* The callsite should not be null here, we would not have
* created the descriptors otherwise
*/
throw new IllegalStateException();
}
if (!(id instanceof String)) {
return null;
}
switch ((String) id) {
case ID_FILE_NAME:
return cs.getFileName();
case ID_LINE_NUMBER:
return nullToEmptyString(cs.getLineNo());
default:
return null;
}
}
@Override
public boolean isPropertySet(Object id) {
return false;
}
@Override
public void resetPropertyValue(Object id) {
}
@Override
public void setPropertyValue(Object id, Object value) {
}
}
private class CustomAttributePropertySource implements IPropertySource {
private final ITmfCustomAttributes event;
public CustomAttributePropertySource(ITmfCustomAttributes event) {
this.event = event;
}
@Override
public Object getEditableValue() {
return EMPTY_STRING;
}
@Override
public IPropertyDescriptor[] getPropertyDescriptors() {
List<IPropertyDescriptor> descriptors = new ArrayList<>();
for (String customAttribute : event.listCustomAttributes()) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(customAttribute, customAttribute));
}
return descriptors.toArray(new IPropertyDescriptor[0]);
}
@Override
public Object getPropertyValue(Object id) {
if (!(id instanceof String)) {
return null;
}
return event.getCustomAttribute((String) id);
}
@Override
public boolean isPropertySet(Object id) {
return false;
}
@Override
public void resetPropertyValue(Object id) {
}
@Override
public void setPropertyValue(Object id, Object value) {
}
}
/**
* Default constructor
*
* @param event the event
*/
public TmfEventPropertySource(ITmfEvent event) {
super();
this.fEvent = event;
}
@Override
public Object getEditableValue() {
return null;
}
@Override
public IPropertyDescriptor[] getPropertyDescriptors() {
List<IPropertyDescriptor> descriptors= new ArrayList<>();
/* Display basic event information */
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TIMESTAMP, NAME_TIMESTAMP));
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TYPE, NAME_TYPE));
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TRACE, NAME_TRACE));
/* Display event fields */
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CONTENT, NAME_CONTENT));
/* Display source lookup information, if the event supplies it */
if ((fEvent instanceof ITmfSourceLookup) && (((ITmfSourceLookup)fEvent).getCallsite() != null)) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_SOURCE_LOOKUP, NAME_SOURCE_LOOKUP));
}
/* Display Model URI information, if the event supplies it */
if ((fEvent instanceof ITmfModelLookup) && (((ITmfModelLookup) fEvent).getModelUri() != null)) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_MODEL_URI, NAME_MODEL_URI));
}
/* Display custom attributes, if available */
if (fEvent instanceof ITmfCustomAttributes) {
ITmfCustomAttributes event = (ITmfCustomAttributes) fEvent;
if (!event.listCustomAttributes().isEmpty()) {
descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CUSTOM_ATTRIBUTE, NAME_CUSTOM_ATTRIBUTES));
}
}
return descriptors.toArray(new IPropertyDescriptor[0]);
}
@Override
public Object getPropertyValue(Object id) {
if (id.equals(ID_TIMESTAMP)) {
return new TimestampPropertySource(fEvent.getTimestamp());
} else if (id.equals(ID_TYPE) && fEvent.getType() != null) {
return fEvent.getType().toString();
} else if (id.equals(ID_TRACE)) {
return fEvent.getTrace().getName();
} else if (id.equals(ID_MODEL_URI)) {
return ((ITmfModelLookup)fEvent).getModelUri();
} else if (id.equals(ID_SOURCE_LOOKUP)) {
return new SourceLookupPropertySource(((ITmfSourceLookup)fEvent));
} else if (id.equals(ID_CONTENT) && fEvent.getContent() != null) {
return new ContentPropertySource(fEvent.getContent());
} else if (id.equals(ID_CUSTOM_ATTRIBUTE)) {
return new CustomAttributePropertySource((ITmfCustomAttributes) fEvent);
}
return null;
}
@Override
public boolean isPropertySet(Object id) {
return false;
}
@Override
public void resetPropertyValue(Object id) {
}
@Override
public void setPropertyValue(Object id, Object value) {
}
}
| tmf: Update event properties to use aspects
By using all defined aspects as property descriptors, we can
do away with some of the hard-coded ones, like timestamp and
even type.
Event content could keep its own descriptor though, since it
puts the event fields into a nice sub-tree.
This also makes sure that any extra aspect defined by the
trace type also shows up in the Properties View.
Signed-off-by: Alexandre Montplaisir <[email protected]>
| tmf/org.eclipse.tracecompass.tmf.ui/src/org/eclipse/tracecompass/tmf/ui/viewers/events/TmfEventPropertySource.java | tmf: Update event properties to use aspects | <ide><path>mf/org.eclipse.tracecompass.tmf.ui/src/org/eclipse/tracecompass/tmf/ui/viewers/events/TmfEventPropertySource.java
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<del>
<add>import java.util.Optional;
<add>import java.util.stream.Stream;
<add>
<add>import org.eclipse.jdt.annotation.NonNull;
<ide> import org.eclipse.tracecompass.tmf.core.event.ITmfCustomAttributes;
<ide> import org.eclipse.tracecompass.tmf.core.event.ITmfEvent;
<ide> import org.eclipse.tracecompass.tmf.core.event.ITmfEventField;
<add>import org.eclipse.tracecompass.tmf.core.event.aspect.ITmfEventAspect;
<add>import org.eclipse.tracecompass.tmf.core.event.aspect.TmfBaseAspects;
<ide> import org.eclipse.tracecompass.tmf.core.event.lookup.ITmfCallsite;
<ide> import org.eclipse.tracecompass.tmf.core.event.lookup.ITmfModelLookup;
<ide> import org.eclipse.tracecompass.tmf.core.event.lookup.ITmfSourceLookup;
<del>import org.eclipse.tracecompass.tmf.core.timestamp.ITmfTimestamp;
<ide> import org.eclipse.tracecompass.tmf.ui.properties.ReadOnlyTextPropertyDescriptor;
<ide> import org.eclipse.ui.views.properties.IPropertyDescriptor;
<ide> import org.eclipse.ui.views.properties.IPropertySource;
<add>import org.lttng.scope.common.core.StreamUtils;
<ide>
<ide> /**
<ide> * Property source for events
<ide> */
<ide> public class TmfEventPropertySource implements IPropertySource {
<ide>
<del> private static final String ID_TIMESTAMP = "event_timestamp"; //$NON-NLS-1$
<del> private static final String ID_TYPE = "event_type"; //$NON-NLS-1$
<del> private static final String ID_TRACE = "trace_attribute"; //$NON-NLS-1$
<ide> private static final String ID_CONTENT = "event_content"; //$NON-NLS-1$
<ide> private static final String ID_SOURCE_LOOKUP = "event_lookup"; //$NON-NLS-1$
<ide> private static final String ID_MODEL_URI = "model_uri"; //$NON-NLS-1$
<ide> private static final String ID_CUSTOM_ATTRIBUTE = "custom_attribute"; //$NON-NLS-1$
<ide>
<del> private static final String NAME_TIMESTAMP = "Timestamp"; //$NON-NLS-1$
<del> private static final String NAME_TYPE = "Type"; //$NON-NLS-1$
<del> private static final String NAME_TRACE = "Trace"; //$NON-NLS-1$
<ide> private static final String NAME_CONTENT = "Content"; //$NON-NLS-1$
<ide> private static final String NAME_SOURCE_LOOKUP = "Source Lookup"; //$NON-NLS-1$
<ide> private static final String NAME_MODEL_URI = "Model URI"; //$NON-NLS-1$
<ide>
<ide> private static final String EMPTY_STRING = ""; //$NON-NLS-1$
<ide>
<del> private ITmfEvent fEvent;
<del>
<del> private static class TimestampPropertySource implements IPropertySource {
<del> private static final String ID_TIMESTAMP_VALUE = "timestamp_value"; //$NON-NLS-1$
<del> private static final String ID_TIMESTAMP_SCALE = "timestamp_scale"; //$NON-NLS-1$
<del> private static final String NAME_TIMESTAMP_VALUE = "value"; //$NON-NLS-1$
<del> private static final String NAME_TIMESTAMP_SCALE = "scale"; //$NON-NLS-1$
<del>
<del> private ITmfTimestamp fTimestamp;
<del>
<del> public TimestampPropertySource(ITmfTimestamp timestamp) {
<del> fTimestamp = timestamp;
<del> }
<del>
<del> @Override
<del> public Object getEditableValue() {
<del> return fTimestamp.toString();
<del> }
<del>
<del> @Override
<del> public IPropertyDescriptor[] getPropertyDescriptors() {
<del> IPropertyDescriptor[] descriptors = new IPropertyDescriptor[2];
<del> descriptors[0] = new ReadOnlyTextPropertyDescriptor(ID_TIMESTAMP_VALUE, NAME_TIMESTAMP_VALUE);
<del> descriptors[1] = new ReadOnlyTextPropertyDescriptor(ID_TIMESTAMP_SCALE, NAME_TIMESTAMP_SCALE);
<del> return descriptors;
<del> }
<del>
<del> @Override
<del> public Object getPropertyValue(Object id) {
<del> if (id.equals(ID_TIMESTAMP_VALUE)) {
<del> return Long.toString(fTimestamp.getValue());
<del> } else if (id.equals(ID_TIMESTAMP_SCALE)) {
<del> return Integer.toString(fTimestamp.getScale());
<del> }
<del> return null;
<del> }
<del>
<del> @Override
<del> public boolean isPropertySet(Object id) {
<del> return false;
<del> }
<del>
<del> @Override
<del> public void resetPropertyValue(Object id) {
<del> }
<del>
<del> @Override
<del> public void setPropertyValue(Object id, Object value) {
<del> }
<del> }
<add> private final @NonNull ITmfEvent fEvent;
<ide>
<ide> private static class ContentPropertySource implements IPropertySource {
<ide> private ITmfEventField fContent;
<ide> *
<ide> * @param event the event
<ide> */
<del> public TmfEventPropertySource(ITmfEvent event) {
<add> public TmfEventPropertySource(@NonNull ITmfEvent event) {
<ide> super();
<ide> this.fEvent = event;
<ide> }
<ide> public IPropertyDescriptor[] getPropertyDescriptors() {
<ide> List<IPropertyDescriptor> descriptors= new ArrayList<>();
<ide>
<del> /* Display basic event information */
<del> descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TIMESTAMP, NAME_TIMESTAMP));
<del> descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TYPE, NAME_TYPE));
<del> descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TRACE, NAME_TRACE));
<del>
<del> /* Display event fields */
<del> descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CONTENT, NAME_CONTENT));
<add> /* Display properties for event aspects */
<add> getTraceAspects().forEach(aspect -> {
<add> /*
<add> * Contents has its special property source, which puts the fields
<add> * in a sub-tree.
<add> */
<add> if (aspect == TmfBaseAspects.getContentsAspect()) {
<add> descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CONTENT, NAME_CONTENT));
<add> } else {
<add> String name = aspect.getName();
<add> descriptors.add(new ReadOnlyTextPropertyDescriptor(name, name));
<add> }
<add> });
<ide>
<ide> /* Display source lookup information, if the event supplies it */
<ide> if ((fEvent instanceof ITmfSourceLookup) && (((ITmfSourceLookup)fEvent).getCallsite() != null)) {
<ide> }
<ide>
<ide> @Override
<del> public Object getPropertyValue(Object id) {
<del> if (id.equals(ID_TIMESTAMP)) {
<del> return new TimestampPropertySource(fEvent.getTimestamp());
<del> } else if (id.equals(ID_TYPE) && fEvent.getType() != null) {
<del> return fEvent.getType().toString();
<del> } else if (id.equals(ID_TRACE)) {
<del> return fEvent.getTrace().getName();
<del> } else if (id.equals(ID_MODEL_URI)) {
<add> public Object getPropertyValue(Object objectId) {
<add> if (!(objectId instanceof String)) {
<add> return null;
<add> }
<add>
<add> String id = (String) objectId;
<add>
<add> if (id.equals(ID_MODEL_URI)) {
<ide> return ((ITmfModelLookup)fEvent).getModelUri();
<ide> } else if (id.equals(ID_SOURCE_LOOKUP)) {
<ide> return new SourceLookupPropertySource(((ITmfSourceLookup)fEvent));
<ide> } else if (id.equals(ID_CUSTOM_ATTRIBUTE)) {
<ide> return new CustomAttributePropertySource((ITmfCustomAttributes) fEvent);
<ide> }
<add>
<add> /* Look for the ID in the aspect names */
<add> Optional<ITmfEventAspect<?>> potentialAspect = getTraceAspects()
<add> .filter(aspect -> aspect.getName().equals(id))
<add> .findFirst();
<add>
<add> if (potentialAspect.isPresent()) {
<add> Object res = potentialAspect.get().resolve(fEvent);
<add> return (res == null ? "" : res.toString()); //$NON-NLS-1$
<add> }
<add>
<ide> return null;
<add> }
<add>
<add> private Stream<ITmfEventAspect<?>> getTraceAspects() {
<add> return StreamUtils.getStream(fEvent.getTrace().getEventAspects());
<ide> }
<ide>
<ide> @Override |
|
Java | mit | f417410cfdba982d2b30f7c242d03dc0bf7e91c3 | 0 | ihongs/HongsCORE,ihongs/HongsCORE,ihongs/HongsCORE | package io.github.ihongs.dh.search;
import io.github.ihongs.Cnst;
import io.github.ihongs.HongsException;
import io.github.ihongs.action.ActionHelper;
import io.github.ihongs.action.ActionRunner;
import io.github.ihongs.action.FormSet;
import io.github.ihongs.action.anno.Action;
import io.github.ihongs.action.anno.Preset;
import io.github.ihongs.action.anno.Select;
import io.github.ihongs.dh.IEntity;
import io.github.ihongs.dh.JAction;
import io.github.ihongs.dh.lucene.LuceneRecord;
import io.github.ihongs.dh.search.TitlesHelper.Titles;
import io.github.ihongs.util.Dict;
import io.github.ihongs.util.Synt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 搜索动作
* @author Hongs
*/
@Action()
public class SearchAction extends JAction {
@Override
public IEntity getEntity(ActionHelper helper)
throws HongsException {
ActionRunner runner = (ActionRunner)
helper.getAttribute(ActionRunner.class.getName());
return SearchEntity.getInstance (runner.getModule(), runner.getEntity());
}
@Action("search")
@Preset(conf="", form="")
@Select(conf="", form="")
@Override
public void search(ActionHelper helper) throws HongsException {
/**
* 有指定查询条件则按匹配度排序
*/
Map rd = helper.getRequestData();
Object wd = rd.get(Cnst.WD_KEY);
if( wd != null && ! "".equals(wd)) {
Set xb = Synt.toTerms (rd.get(Cnst.OB_KEY));
List ob ;
if( xb == null) {
ob = new ArrayList( 1);
rd.put(Cnst.OB_KEY, ob);
ob.add( 0 , "-");
} else
if(!xb.contains("-")
&& !xb.contains("*")) {
ob = new ArrayList(xb);
rd.put(Cnst.OB_KEY, ob);
ob.add( 0 , "-");
}
}
super.search(helper);
}
@Action("acount")
@Preset(conf="", form="")
@Titles(conf="", form="")
public void acount(ActionHelper helper) throws HongsException {
SearchEntity sr = (SearchEntity) getEntity(helper);
StatisHelper sh = new StatisHelper(sr);
Map rd = helper.getRequestData();
rd = getReqMap(helper, sr, "acount", rd);
// 检查参数
acheck(sr, rd, 1 );
Map xd = sh.acount ( rd );
Map sd = Synt.mapOf("enfo", xd );
sd = getRspMap(helper, sr, "acount", sd);
helper.reply( sd );
}
@Action("amount")
@Preset(conf="", form="")
@Titles(conf="", form="")
public void amount(ActionHelper helper) throws HongsException {
SearchEntity sr = (SearchEntity) getEntity(helper);
StatisHelper sh = new StatisHelper(sr);
Map rd = helper.getRequestData();
rd = getReqMap(helper, sr, "amount", rd);
// 检查参数
acheck(sr, rd, 2 );
Map xd = sh.amount ( rd );
Map sd = Synt.mapOf("enfo", xd );
sd = getRspMap(helper, sr, "amount", sd);
helper.reply( sd );
}
@Action("assort")
@Preset(conf="", form="")
@Select(conf="", form="")
public void assort(ActionHelper helper) throws HongsException {
SearchEntity sr = (SearchEntity) getEntity(helper);
StatisHelper sh = new StatisHelper(sr);
Map rd = helper.getRequestData();
rd = getReqMap(helper, sr, "assort", rd);
// 检查参数
acheck(sr, rd, 3 );
int rn = Synt.declare(rd.get(Cnst.RN_KEY), 0);
int pn = Synt.declare(rd.get(Cnst.PN_KEY), 1);
Map sd = sh.assort(rd, rn, pn);
sd = getRspMap(helper, sr, "assort", sd);
helper.reply( sd );
}
/**
* 检查参数是否可统计
* @param sr 字段配置
* @param rd 请求数据
* @param nb 1 acount, 2 amount, 3 assort
* @throws HongsException
*/
protected void acheck(LuceneRecord sr, Map rd, int nb) throws HongsException {
Set rb = Synt.toTerms(rd.get(Cnst.RB_KEY));
Set ob = Synt.toTerms(rd.get(Cnst.OB_KEY));
Map fs = sr.getFields( );
Map ts = FormSet.getInstance( ).getEnum("__types__");
String cn = Dict.getValue(fs, "default", "@","conf");
// String nn = Dict.getValue(fs, "unknown", "@","form");
// 字段限定
Set ns ;
Set ks = NUM_KINDS;
Set hs = CAL_HANDS;
if (nb < ACT_NAMES.length) {
ns = sr.getCaseNames(ACT_NAMES[nb] + "able");
if (ns == null || ns.isEmpty()) {
ns = sr.getCaseNames("statable");
}} else {
ns = sr.getCaseNames("statable");
}
if (rb != null ) for (Object fu : rb) {
String fn = null != fu ? fu.toString() : "";
String fx = null ;
/**
* 分组统计:
* 维度字段后跟函数名,
* 判断前需要将其去除.
*/
if (nb == 3) {
int p = fn.indexOf ('!');
if (p != -1) {
fx = fn.substring(1+p);
fn = fn.substring(0,p);
// 统计行数
if (fx.equals("count")
&& fn.equals( "*" ) ) {
continue;
}
}
}
Map fc = (Map)fs.get(fn);
if (! fs.containsKey(fn)) {
throw new HongsException(400, "Field '"+fn+"' is not existent");
}
if (! ns.contains (fn)) {
throw new HongsException(400, "Field '"+fn+"' is not statable");
}
/**
* 数值统计:
* 仅数字类型可以计算,
* 分组计算方法也一样.
*/
if (nb == 2
|| (nb == 3 && hs.contains(fx)) ) {
Object t = fc.get("__type__");
Object k = fc.get( "type" );
t = ts.containsKey(t) ? ts.get(t) : t;
if (! "number".equals(t)
&& ! "date" .equals(t)
&& !("hidden".equals(t) && ks.contains(k))
&& !( "enum" .equals(t) && ks.contains(k))) {
throw new HongsException(400, "Field '"+fn+"' is not numeric");
}
/**
* 枚举补全:
* 如果外部未指定区间,
* 则从枚举配置中提取.
*/
Set on = Dict.getValue(rd, Set.class, fn, StatisHelper.ON_REL);
if (on == null) {
String xc = Synt.defxult((String) fc.get("conf"), (String) cn);
String xn = Synt.defxult((String) fc.get("enum"), (String) fn);
try {
on = FormSet.getInstance(xc).getEnum(xn).keySet();
Dict.put(rd , on , fn , StatisHelper.ON_REL);
} catch ( HongsException ex) {
if (ex.getErrno() != 913) {
throw ex;
}}
}
}
}
if (ob != null ) for (Object fu : ob) {
String fn = fu != null ? fu.toString() : "";
/**
* 非聚合统计中
* ! 表默认逆序
* * 表默认正序
*/
if (nb != 3
&& (fn.equals("-")
|| fn.equals("!")
|| fn.equals("*") ) ) {
continue;
}
/**
* 排序字段:
* 对返回的列表排序时,
* 无效字段会影响效率,
* 故对照查询字段检查.
*/
if (fn.startsWith("-") ) {
fn = fn.substring(1);
} else
if (fn. endsWith("!") ) {
fn = fn.substring(0, fn.length() - 1);
}
if (rb == null || ! rb.contains(fn)) {
throw new HongsException(400, "Field '"+fu+"' can not be sorted");
}
}
}
private static final String [ ] ACT_NAMES = new String [] {"", "acount", "amount", "assort"}; // 统计名称
private static final Set<String> CAL_HANDS = new HashSet(Arrays.asList("sum", "min" , "max" , "ratio" , "range" )); // 计算方法
private static final Set<String> NUM_KINDS = new HashSet(Arrays.asList("int", "long", "float", "double", "number")); // 数字类型
}
| hongs-serv-search/src/main/java/io/github/ihongs/dh/search/SearchAction.java | package io.github.ihongs.dh.search;
import io.github.ihongs.Cnst;
import io.github.ihongs.HongsException;
import io.github.ihongs.action.ActionHelper;
import io.github.ihongs.action.ActionRunner;
import io.github.ihongs.action.FormSet;
import io.github.ihongs.action.anno.Action;
import io.github.ihongs.action.anno.Preset;
import io.github.ihongs.action.anno.Select;
import io.github.ihongs.dh.IEntity;
import io.github.ihongs.dh.JAction;
import io.github.ihongs.dh.lucene.LuceneRecord;
import io.github.ihongs.dh.search.TitlesHelper.Titles;
import io.github.ihongs.util.Dict;
import io.github.ihongs.util.Synt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 搜索动作
* @author Hongs
*/
@Action()
public class SearchAction extends JAction {
@Override
public IEntity getEntity(ActionHelper helper)
throws HongsException {
ActionRunner runner = (ActionRunner)
helper.getAttribute(ActionRunner.class.getName());
return SearchEntity.getInstance (runner.getModule(), runner.getEntity());
}
@Action("search")
@Preset(conf="", form="")
@Select(conf="", form="")
@Override
public void search(ActionHelper helper) throws HongsException {
/**
* 有指定查询条件则按匹配度排序
*/
Map rd = helper.getRequestData();
Object wd = rd.get(Cnst.WD_KEY);
if( wd != null && ! "".equals(wd)) {
Set xb = Synt.toTerms (rd.get(Cnst.OB_KEY));
List ob ;
if( xb == null) {
ob = new ArrayList( 1);
rd.put(Cnst.OB_KEY, ob);
ob.add( 0 , "-");
} else
if(!xb.contains("-")
&& !xb.contains("*")) {
ob = new ArrayList(xb);
rd.put(Cnst.OB_KEY, ob);
ob.add( 0 , "-");
}
}
super.search(helper);
}
@Action("acount")
@Preset(conf="", form="")
@Titles(conf="", form="")
public void acount(ActionHelper helper) throws HongsException {
SearchEntity sr = (SearchEntity) getEntity(helper);
StatisHelper sh = new StatisHelper(sr);
Map rd = helper.getRequestData();
rd = getReqMap(helper, sr, "acount", rd);
// 检查参数
acheck(sr, rd, 1 );
Map xd = sh.acount ( rd );
Map sd = Synt.mapOf("enfo", xd );
sd = getRspMap(helper, sr, "acount", sd);
helper.reply( sd );
}
@Action("amount")
@Preset(conf="", form="")
@Titles(conf="", form="")
public void amount(ActionHelper helper) throws HongsException {
SearchEntity sr = (SearchEntity) getEntity(helper);
StatisHelper sh = new StatisHelper(sr);
Map rd = helper.getRequestData();
rd = getReqMap(helper, sr, "amount", rd);
// 检查参数
acheck(sr, rd, 2 );
Map xd = sh.amount ( rd );
Map sd = Synt.mapOf("enfo", xd );
sd = getRspMap(helper, sr, "amount", sd);
helper.reply( sd );
}
@Action("assort")
@Preset(conf="", form="")
@Select(conf="", form="")
public void assort(ActionHelper helper) throws HongsException {
SearchEntity sr = (SearchEntity) getEntity(helper);
StatisHelper sh = new StatisHelper(sr);
Map rd = helper.getRequestData();
rd = getReqMap(helper, sr, "assort", rd);
// 检查参数
acheck(sr, rd, 3 );
int rn = Synt.declare(rd.get(Cnst.RN_KEY), 0);
int pn = Synt.declare(rd.get(Cnst.PN_KEY), 1);
Map sd = sh.assort(rd, rn, pn);
sd = getRspMap(helper, sr, "assort", sd);
helper.reply( sd );
}
/**
* 检查参数是否可统计
* @param sr 字段配置
* @param rd 请求数据
* @param nb 1 acount, 2 amount, 3 assort
* @throws HongsException
*/
protected void acheck(LuceneRecord sr, Map rd, int nb) throws HongsException {
Set rb = Synt.toTerms(rd.get(Cnst.RB_KEY));
Set ob = Synt.toTerms(rd.get(Cnst.OB_KEY));
Map fs = sr.getFields( );
Map ts = FormSet.getInstance( ).getEnum("__types__");
String cn = Dict.getValue(fs, "default", "@","conf");
// String nn = Dict.getValue(fs, "unknown", "@","form");
// 字段限定
Set ns ;
Set ks = NUM_KINDS;
Set hs = CAL_HANDS;
if (nb < ACT_NAMES.length) {
ns = sr.getCaseNames(ACT_NAMES[nb] + "able");
if (ns == null || ns.isEmpty()) {
ns = sr.getCaseNames("statable");
}} else {
ns = sr.getCaseNames("statable");
}
if (rb != null ) for (Object fu : rb) {
String fn = null != fu ? fu.toString() : "";
String fx = null ;
/**
* 分组统计:
* 维度字段后跟函数名,
* 判断前需要将其去除.
*/
if (nb == 3) {
int p = fn.indexOf ('!');
if (p != -1) {
fx = fn.substring(1+p);
fn = fn.substring(0,p);
// 统计行数
if (fx.equals("count")
&& fn.equals( "*" ) ) {
continue;
}
}
}
Map fc = (Map)fs.get(fn);
if (! fs.containsKey(fn)) {
throw new HongsException(400, "Field '"+fn+"' is not existent");
}
if (! ns.contains (fn)) {
throw new HongsException(400, "Field '"+fn+"' is not statable");
}
/**
* 数值统计:
* 仅数字类型可以计算,
* 分组计算方法也一样.
*/
if (nb == 2
|| (nb == 3 && hs.contains(fx)) ) {
Object t = fc.get("__type__");
Object k = fc.get( "type" );
t = ts.containsKey(t) ? ts.get(t) : t;
if (! "number".equals(t)
&& ! "date" .equals(t)
&& !("hidden".equals(t) && ks.contains(k))
&& !( "enum" .equals(t) && ks.contains(k))) {
throw new HongsException(400, "Field '"+fn+"' is not numeric");
}
/**
* 枚举补全:
* 如果外部未指定区间,
* 则从枚举配置中提取.
*/
Set on = Dict.getValue(rd, Set.class, fn, StatisHelper.ON_REL);
if (on == null) {
String xc = Synt.defxult((String) fc.get("conf"), (String) cn);
String xn = Synt.defxult((String) fc.get("enum"), (String) fn);
try {
on = FormSet.getInstance(xc).getEnum(xn).keySet();
Dict.put(rd , on , fn , StatisHelper.ON_REL);
} catch ( HongsException ex) {
if (ex.getErrno() != 913) {
throw ex;
}}
}
}
}
if (ob != null ) for (Object fu : ob) {
String fn = fu != null ? fu.toString() : "";
/**
* 非聚合统计中
* ! 表默认逆序
* * 表默认正序
*/
if (nb != 3
&& (fn.equals("-")
|| fn.equals("!")
|| fn.equals("*") ) ) {
continue;
}
/**
* 排序字段:
* 对返回的列表排序时,
* 无效字段会影响效率,
* 故对照查询字段检查.
*/
if (fn.startsWith("-") ) {
fn = fn.substring(1);
} else
if (fn. endsWith("!") ) {
fn = fn.substring(0, fn.length() - 1);
}
if (rb == null || ! rb.contains(fn)) {
throw new HongsException(400, "Field '"+fu+"' can not be sorted");
}
}
}
private static final String [ ] ACT_NAMES = new String [] {"", "acount", "amount", "assort"}; // 统计名称
private static final Set<String> CAL_HANDS = new HashSet(Arrays.asList("sum", "min" , "max" , "ratio" , "range" )); // 计算方法
private static final Set<String> NUM_KINDS = new HashSet(Arrays.asList("int", "long", "float", "double", "number")); // 数字类型
}
| 重写统计方法 | hongs-serv-search/src/main/java/io/github/ihongs/dh/search/SearchAction.java | 重写统计方法 | <ide><path>ongs-serv-search/src/main/java/io/github/ihongs/dh/search/SearchAction.java
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<del>import java.util.HashMap;
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide> import java.util.Map; |
|
JavaScript | mit | b91c87de1954576ecd6839323eda8cd666a4118f | 0 | grimor/sculptgl,stephomi/sculptgl,nonconforme/sculptgl,beni55/sculptgl,ytiurin/sculptgl,stephomi/sculptgl,ytiurin/sculptgl,anteaterho/sculptgl,grimor/sculptgl,anteaterho/sculptgl,nonconforme/sculptgl,beni55/sculptgl | define([
'lib/glMatrix',
'misc/Utils',
'math3d/Geometry',
'editor/tools/Smooth'
], function (glm, Utils, Geometry, Smooth) {
'use strict';
var vec3 = glm.vec3;
var Subdivision = function (mesh) {
this.mesh_ = mesh;
this.linear_ = false; // linear subdivision
this.verticesMap_ = new Map(); // to detect new vertices at the middle of edge (for subdivision)
this.states_ = null; // for undo-redo
this.center_ = [0.0, 0.0, 0.0]; // center point of select sphere
this.radius2_ = 0.0; // radius squared of select sphere
this.edgeMax2_ = 0.0; // maximal squared edge length before we subdivide it
};
Subdivision.prototype = {
/** Subdivide until every selected triangles comply with a detail level */
subdivision: function (iTris, center, radius2, detail2, states) {
vec3.copy(this.center_, center);
this.radius2_ = radius2;
this.edgeMax2_ = detail2;
this.states_ = states;
var mesh = this.mesh_;
var nbTriangles = 0;
while (nbTriangles !== mesh.getNbTriangles()) {
nbTriangles = mesh.getNbTriangles();
iTris = this.subdivide(iTris);
}
return iTris;
},
/**
* Subdivide a set of triangle. Main steps are :
* 1. Detect the triangles that need to be split, and at which edge the split should occur
* 2. Subdivide all those triangles (split them in two)
* 3. Take the 2-ring neighborhood of the triangles that have been split
* 4. Fill the triangles (just create an edge where it's needed)
* 5. Smooth newly created vertices (along the plane defined by their own normals)
* 6. Tag the newly created vertices if they are inside the sculpt brush radius
*/
subdivide: function (iTris) {
var mesh = this.mesh_;
var nbVertsInit = mesh.getNbVertices();
var nbTrisInit = mesh.getNbTriangles();
this.verticesMap_ = new Map();
var res = this.initSplit(iTris);
var iTrisSubd = res[0];
var split = res[1];
if (iTrisSubd.length > 5) {
iTrisSubd = mesh.expandsFaces(iTrisSubd, 3);
split = new Uint8Array(iTrisSubd.length);
split.set(res[1]);
}
// undo-redo
this.states_.pushVertices(mesh.getVerticesFromFaces(iTrisSubd));
this.states_.pushFaces(iTrisSubd);
mesh.reAllocateArrays(split.length);
this.subdivideTriangles(iTrisSubd, split);
var i = 0;
var nbNewTris = mesh.getNbTriangles() - nbTrisInit;
var newTriangles = new Uint32Array(nbNewTris);
for (i = 0; i < nbNewTris; ++i)
newTriangles[i] = nbTrisInit + i;
newTriangles = mesh.expandsFaces(newTriangles, 1);
// undo-redo
iTrisSubd = newTriangles.subarray(nbNewTris);
this.states_.pushVertices(mesh.getVerticesFromFaces(iTrisSubd));
this.states_.pushFaces(iTrisSubd);
var temp = iTris;
var nbTris = iTris.length;
iTris = new Uint32Array(nbTris + newTriangles.length);
iTris.set(temp);
iTris.set(newTriangles, nbTris);
var ftf = mesh.getFacesTagFlags();
var nbTrisMask = iTris.length;
var iTrisMask = new Uint32Array(Utils.getMemory(nbTrisMask * 4), 0, nbTrisMask);
var nbTriMask = 0;
var tagFlag = ++Utils.TAG_FLAG;
for (i = 0; i < nbTrisMask; ++i) {
var iTri = iTris[i];
if (ftf[iTri] === tagFlag)
continue;
ftf[iTri] = tagFlag;
iTrisMask[nbTriMask++] = iTri;
}
iTrisMask = new Uint32Array(iTrisMask.subarray(0, nbTriMask));
var nbTrianglesOld = mesh.getNbTriangles();
while (newTriangles.length > 0) {
mesh.reAllocateArrays(newTriangles.length);
newTriangles = this.fillTriangles(newTriangles);
}
nbNewTris = mesh.getNbTriangles() - nbTrianglesOld;
temp = iTrisMask;
iTrisMask = new Uint32Array(nbTriMask + nbNewTris);
iTrisMask.set(temp);
for (i = 0; i < nbNewTris; ++i)
iTrisMask[nbTriMask + i] = nbTrianglesOld + i;
var nbVNew = mesh.getNbVertices() - nbVertsInit;
var vNew = new Uint32Array(nbVNew);
for (i = 0; i < nbVNew; ++i)
vNew[i] = nbVertsInit + i;
vNew = mesh.expandsVertices(vNew, 1);
if (!this.linear_) {
var smo = new Smooth();
smo.mesh_ = mesh;
var expV = vNew.subarray(nbVNew);
smo.smoothTangent(expV, 1.0);
mesh.updateTopology(mesh.getFacesFromVertices(expV));
}
var vAr = mesh.getVertices();
var vscf = mesh.getVerticesSculptFlags();
var centerPoint = this.center_;
var xcen = centerPoint[0];
var ycen = centerPoint[1];
var zcen = centerPoint[2];
var vertexSculptMask = Utils.SCULPT_FLAG;
nbVNew = vNew.length;
for (i = 0; i < nbVNew; ++i) {
var ind = vNew[i];
var j = ind * 3;
var dx = vAr[j] - xcen;
var dy = vAr[j + 1] - ycen;
var dz = vAr[j + 2] - zcen;
vscf[ind] = (dx * dx + dy * dy + dz * dz) < this.radius2_ ? vertexSculptMask : vertexSculptMask - 1;
}
return iTrisMask;
},
/** Detect which triangles to split and the edge that need to be split */
initSplit: function (iTris) {
var nbTris = iTris.length;
var buffer = Utils.getMemory((4 + 1) * nbTris);
var iTrisSubd = new Uint32Array(buffer, 0, nbTris);
var split = new Uint8Array(buffer, 4 * nbTris, nbTris);
var acc = 0;
for (var i = 0; i < nbTris; ++i) {
var iTri = iTris[i];
var splitNum = this.findSplit(iTri, true);
if (splitNum === 0) continue;
split[acc] = splitNum;
iTrisSubd[acc++] = iTri;
}
return [new Uint32Array(iTrisSubd.subarray(0, acc)), new Uint8Array(split.subarray(0, acc))];
},
/** Find the edge to be split (0 otherwise) */
findSplit: (function () {
var v1 = [0.0, 0.0, 0.0];
var v2 = [0.0, 0.0, 0.0];
var v3 = [0.0, 0.0, 0.0];
var tis = Geometry.triangleInsideSphere;
var pit = Geometry.pointInsideTriangle;
return function (iTri, checkInsideSphere) {
var mesh = this.mesh_;
var vAr = mesh.getVertices();
var fAr = mesh.getFaces();
var id = iTri * 4;
var ind1 = fAr[id] * 3;
var ind2 = fAr[id + 1] * 3;
var ind3 = fAr[id + 2] * 3;
v1[0] = vAr[ind1];
v1[1] = vAr[ind1 + 1];
v1[2] = vAr[ind1 + 2];
v2[0] = vAr[ind2];
v2[1] = vAr[ind2 + 1];
v2[2] = vAr[ind2 + 2];
v3[0] = vAr[ind3];
v3[1] = vAr[ind3 + 1];
v3[2] = vAr[ind3 + 2];
if (checkInsideSphere && !tis(this.center_, this.radius2_, v1, v2, v3) && !pit(this.center_, v1, v2, v3))
return 0;
var length1 = vec3.sqrDist(v1, v2);
var length2 = vec3.sqrDist(v2, v3);
var length3 = vec3.sqrDist(v1, v3);
if (length1 > length2 && length1 > length3) return length1 > this.edgeMax2_ ? 1 : 0;
else if (length2 > length3) return length2 > this.edgeMax2_ ? 2 : 0;
else return length3 > this.edgeMax2_ ? 3 : 0;
};
})(),
/** Subdivide all the triangles that need to be subdivided */
subdivideTriangles: function (iTrisSubd, split) {
var fAr = this.mesh_.getFaces();
var nbTris = iTrisSubd.length;
for (var i = 0; i < nbTris; ++i) {
var iTri = iTrisSubd[i];
var splitNum = split[i];
if (splitNum === 0) splitNum = this.findSplit(iTri);
var ind = iTri * 4;
if (splitNum === 1) this.halfEdgeSplit(iTri, fAr[ind], fAr[ind + 1], fAr[ind + 2]);
else if (splitNum === 2) this.halfEdgeSplit(iTri, fAr[ind + 1], fAr[ind + 2], fAr[ind]);
else if (splitNum === 3) this.halfEdgeSplit(iTri, fAr[ind + 2], fAr[ind], fAr[ind + 1]);
}
},
/**
* Subdivide one triangle, it simply cut the triangle in two at a given edge.
* The position of the vertex is computed as follow :
* 1. Initial position of the new vertex at the middle of the edge
* 2. Compute normal of the new vertex (average of the two normals of the two vertices defining the edge)
* 3. Compute angle between those two normals
* 4. Move the new vertex along its normal with a strengh proportional to the angle computed at step 3.
*/
halfEdgeSplit: function (iTri, iv1, iv2, iv3) {
var mesh = this.mesh_;
var vAr = mesh.getVertices();
var nAr = mesh.getNormals();
var cAr = mesh.getColors();
var mAr = mesh.getMaterials();
var fAr = mesh.getFaces();
var pil = mesh.getFacePosInLeaf();
var fleaf = mesh.getFaceLeaf();
var vrv = mesh.getVerticesRingVert();
var vrf = mesh.getVerticesRingFace();
var fstf = mesh.getFacesStateFlags();
var vstf = mesh.getVerticesStateFlags();
var vMap = this.verticesMap_;
var key = Math.min(iv1, iv2) + '+' + Math.max(iv1, iv2);
var isNewVertex = false;
var ivMid = vMap.get(key);
if (ivMid === undefined) {
ivMid = mesh.getNbVertices();
isNewVertex = true;
vMap.set(key, ivMid);
}
vrv[iv3].push(ivMid);
var id = iTri * 4;
fAr[id] = iv1;
fAr[id + 1] = ivMid;
fAr[id + 2] = iv3;
fAr[id + 3] = -1;
var iNewTri = mesh.getNbTriangles();
id = iNewTri * 4;
fAr[id] = ivMid;
fAr[id + 1] = iv2;
fAr[id + 2] = iv3;
fAr[id + 3] = -1;
fstf[iNewTri] = Utils.STATE_FLAG;
vrf[iv3].push(iNewTri);
Utils.replaceElement(vrf[iv2], iTri, iNewTri);
var leaf = fleaf[iTri];
var iTrisLeaf = leaf.iFaces_;
fleaf[iNewTri] = leaf;
pil[iNewTri] = iTrisLeaf.length;
iTrisLeaf.push(iNewTri);
if (!isNewVertex) {
vrv[ivMid].push(iv3);
vrf[ivMid].push(iTri, iNewTri);
mesh.addNbFace(1);
return;
}
//new vertex
var iNewVer = mesh.getNbVertices();
var id1 = iv1 * 3;
var v1x = vAr[id1];
var v1y = vAr[id1 + 1];
var v1z = vAr[id1 + 2];
var n1x = nAr[id1];
var n1y = nAr[id1 + 1];
var n1z = nAr[id1 + 2];
var id2 = iv2 * 3;
var v2x = vAr[id2];
var v2y = vAr[id2 + 1];
var v2z = vAr[id2 + 2];
var n2x = nAr[id2];
var n2y = nAr[id2 + 1];
var n2z = nAr[id2 + 2];
var n1n2x = n1x + n2x;
var n1n2y = n1y + n2y;
var n1n2z = n1z + n2z;
id = iNewVer * 3;
nAr[id] = n1n2x * 0.5;
nAr[id + 1] = n1n2y * 0.5;
nAr[id + 2] = n1n2z * 0.5;
cAr[id] = (cAr[id1] + cAr[id2]) * 0.5;
cAr[id + 1] = (cAr[id1 + 1] + cAr[id2 + 1]) * 0.5;
cAr[id + 2] = (cAr[id1 + 2] + cAr[id2 + 2]) * 0.5;
mAr[id] = (mAr[id1] + mAr[id2]) * 0.5;
mAr[id + 1] = (mAr[id1 + 1] + mAr[id2 + 1]) * 0.5;
mAr[id + 2] = (mAr[id1 + 2] + mAr[id2 + 2]) * 0.5;
var offset = 0;
if (this.linear_) {
vAr[id] = (v1x + v2x) * 0.5;
vAr[id + 1] = (v1y + v2y) * 0.5;
vAr[id + 2] = (v1z + v2z) * 0.5;
} else {
var len = 1.0 / Math.sqrt(n1x * n1x + n1y * n1y + n1z * n1z);
n1x *= len;
n1y *= len;
n1z *= len;
len = 1.0 / Math.sqrt(n2x * n2x + n2y * n2y + n2z * n2z);
n2x *= len;
n2y *= len;
n2z *= len;
var dot = n1x * n2x + n1y * n2y + n1z * n2z;
var angle = 0;
if (dot <= -1) angle = Math.PI;
else if (dot >= 1) angle = 0;
else angle = Math.acos(dot);
var edgex = v1x - v2x;
var edgey = v1y - v2y;
var edgez = v1z - v2z;
offset = angle * 0.12;
offset *= Math.sqrt(edgex * edgex + edgey * edgey + edgez * edgez);
offset /= Math.sqrt(n1n2x * n1n2x + n1n2y * n1n2y + n1n2z * n1n2z);
if ((edgex * (n1x - n2x) + edgey * (n1y - n2y) + edgez * (n1z - n2z)) < 0)
offset = -offset;
vAr[id] = (v1x + v2x) * 0.5 + n1n2x * offset;
vAr[id + 1] = (v1y + v2y) * 0.5 + n1n2y * offset;
vAr[id + 2] = (v1z + v2z) * 0.5 + n1n2z * offset;
}
vstf[iNewVer] = Utils.STATE_FLAG;
vrv[iNewVer] = [iv1, iv2, iv3];
vrf[iNewVer] = [iTri, iNewTri];
Utils.replaceElement(vrv[iv1], iv2, ivMid);
Utils.replaceElement(vrv[iv2], iv1, ivMid);
mesh.addNbVertice(1);
mesh.addNbFace(1);
},
/**
* Fill the triangles. It checks if a newly vertex has been created at the middle
* of the edge. If several split are needed, it first chooses the split that minimize
* the valence of the vertex.
*/
fillTriangles: function (iTris) {
var mesh = this.mesh_;
var vrv = mesh.getVerticesRingVert();
var fAr = mesh.getFaces();
var nbTris = iTris.length;
var iTrisNext = new Uint32Array(Utils.getMemory(4 * 2 * nbTris), 0, 2 * nbTris);
var nbNext = 0;
var vMap = this.verticesMap_;
for (var i = 0; i < nbTris; ++i) {
var iTri = iTris[i];
var j = iTri * 4;
var iv1 = fAr[j];
var iv2 = fAr[j + 1];
var iv3 = fAr[j + 2];
var val1 = vMap.get(Math.min(iv1, iv2) + '+' + Math.max(iv1, iv2));
var val2 = vMap.get(Math.min(iv2, iv3) + '+' + Math.max(iv2, iv3));
var val3 = vMap.get(Math.min(iv1, iv3) + '+' + Math.max(iv1, iv3));
var num1 = vrv[iv1].length;
var num2 = vrv[iv2].length;
var num3 = vrv[iv3].length;
var split = 0;
if (val1) {
if (val2) {
if (val3) {
if (num1 < num2 && num1 < num3) split = 2;
else if (num2 < num3) split = 3;
else split = 1;
} else if (num1 < num3) split = 2;
else split = 1;
} else if (val3 && num2 < num3) split = 3;
else split = 1;
} else if (val2) {
if (val3 && num2 < num1) split = 3;
else split = 2;
} else if (val3) split = 3;
if (split === 1) this.fillTriangle(iTri, iv1, iv2, iv3, val1);
else if (split === 2) this.fillTriangle(iTri, iv2, iv3, iv1, val2);
else if (split === 3) this.fillTriangle(iTri, iv3, iv1, iv2, val3);
else continue;
iTrisNext[nbNext++] = iTri;
iTrisNext[nbNext++] = mesh.getNbTriangles() - 1;
}
return new Uint32Array(iTrisNext.subarray(0, nbNext));
},
/** Fill crack on one triangle */
fillTriangle: function (iTri, iv1, iv2, iv3, ivMid) {
var mesh = this.mesh_;
var vrv = mesh.getVerticesRingVert();
var vrf = mesh.getVerticesRingFace();
var pil = mesh.getFacePosInLeaf();
var fleaf = mesh.getFaceLeaf();
var fstf = mesh.getFacesStateFlags();
var fAr = mesh.getFaces();
var j = iTri * 4;
fAr[j] = iv1;
fAr[j + 1] = ivMid;
fAr[j + 2] = iv3;
fAr[j + 3] = -1;
var leaf = fleaf[iTri];
var iTrisLeaf = leaf.iFaces_;
vrv[ivMid].push(iv3);
vrv[iv3].push(ivMid);
var iNewTri = mesh.getNbTriangles();
vrf[ivMid].push(iTri, iNewTri);
j = iNewTri * 4;
fAr[j] = ivMid;
fAr[j + 1] = iv2;
fAr[j + 2] = iv3;
fAr[j + 3] = -1;
fstf[iNewTri] = Utils.STATE_FLAG;
fleaf[iNewTri] = leaf;
pil[iNewTri] = iTrisLeaf.length;
vrf[iv3].push(iNewTri);
Utils.replaceElement(vrf[iv2], iTri, iNewTri);
iTrisLeaf.push(iNewTri);
mesh.addNbFace(1);
}
};
return Subdivision;
}); | src/mesh/dynamic/Subdivision.js | define([
'lib/glMatrix',
'misc/Utils',
'math3d/Geometry',
'editor/tools/Smooth'
], function (glm, Utils, Geometry, Smooth) {
'use strict';
var vec3 = glm.vec3;
var Subdivision = function (mesh) {
this.mesh_ = mesh;
this.linear_ = false; // linear subdivision
this.verticesMap_ = new Map(); // to detect new vertices at the middle of edge (for subdivision)
this.states_ = null; // for undo-redo
this.center_ = [0.0, 0.0, 0.0]; // center point of select sphere
this.radius2_ = 0.0; // radius squared of select sphere
this.edgeMax2_ = 0.0; // maximal squared edge length before we subdivide it
};
Subdivision.prototype = {
/** Subdivide until every selected triangles comply with a detail level */
subdivision: function (iTris, center, radius2, detail2, states) {
vec3.copy(this.center_, center);
this.radius2_ = radius2;
this.edgeMax2_ = detail2;
this.states_ = states;
var mesh = this.mesh_;
var nbTriangles = 0;
while (nbTriangles !== mesh.getNbTriangles()) {
nbTriangles = mesh.getNbTriangles();
iTris = this.subdivide(iTris);
}
return iTris;
},
/**
* Subdivide a set of triangle. Main steps are :
* 1. Detect the triangles that need to be split, and at which edge the split should occur
* 2. Subdivide all those triangles (split them in two)
* 3. Take the 2-ring neighborhood of the triangles that have been split
* 4. Fill the triangles (just create an edge where it's needed)
* 5. Smooth newly created vertices (along the plane defined by their own normals)
* 6. Tag the newly created vertices if they are inside the sculpt brush radius
*/
subdivide: function (iTris) {
var mesh = this.mesh_;
var nbVertsInit = mesh.getNbVertices();
var nbTrisInit = mesh.getNbTriangles();
this.verticesMap_ = new Map();
var res = this.initSplit(iTris);
var iTrisSubd = res[0];
var split = res[1];
if (iTrisSubd.length > 5) {
iTrisSubd = mesh.expandsFaces(iTrisSubd, 3);
split = new Uint8Array(iTrisSubd.length);
split.set(res[1]);
}
// undo-redo
this.states_.pushVertices(mesh.getVerticesFromFaces(iTrisSubd));
this.states_.pushFaces(iTrisSubd);
mesh.reAllocateArrays(split.length);
this.subdivideTriangles(iTrisSubd, split);
var i = 0;
var nbNewTris = mesh.getNbTriangles() - nbTrisInit;
var newTriangles = new Uint32Array(nbNewTris);
for (i = 0; i < nbNewTris; ++i)
newTriangles[i] = nbTrisInit + i;
newTriangles = mesh.expandsFaces(newTriangles, 1);
// undo-redo
iTrisSubd = newTriangles.subarray(nbNewTris);
this.states_.pushVertices(mesh.getVerticesFromFaces(iTrisSubd));
this.states_.pushFaces(iTrisSubd);
var temp = iTris;
var nbTris = iTris.length;
iTris = new Uint32Array(nbTris + newTriangles.length);
iTris.set(temp);
iTris.set(newTriangles, nbTris);
var ftf = mesh.getFacesTagFlags();
var nbTrisMask = iTris.length;
var iTrisMask = new Uint32Array(Utils.getMemory(nbTrisMask * 4), 0, nbTrisMask);
var nbTriMask = 0;
var tagFlag = ++Utils.TAG_FLAG;
for (i = 0; i < nbTrisMask; ++i) {
var iTri = iTris[i];
if (ftf[iTri] === tagFlag)
continue;
ftf[iTri] = tagFlag;
iTrisMask[nbTriMask++] = iTri;
}
iTrisMask = new Uint32Array(iTrisMask.subarray(0, nbTriMask));
var nbTrianglesOld = mesh.getNbTriangles();
while (newTriangles.length > 0) {
mesh.reAllocateArrays(newTriangles.length);
newTriangles = this.fillTriangles(newTriangles);
}
nbNewTris = mesh.getNbTriangles() - nbTrianglesOld;
temp = iTrisMask;
iTrisMask = new Uint32Array(nbTriMask + nbNewTris);
iTrisMask.set(temp);
for (i = 0; i < nbNewTris; ++i)
iTrisMask[nbTriMask + i] = nbTrianglesOld + i;
var nbVNew = mesh.getNbVertices() - nbVertsInit;
var vNew = new Uint32Array(nbVNew);
for (i = 0; i < nbVNew; ++i)
vNew[i] = nbVertsInit + i;
vNew = mesh.expandsVertices(vNew, 1);
if (!this.linear_) {
var smo = new Smooth();
smo.mesh_ = mesh;
var expV = vNew.subarray(nbVNew);
smo.smoothTangent(expV, 1.0);
mesh.updateTopology(mesh.getFacesFromVertices(expV));
}
var vAr = mesh.getVertices();
var vscf = mesh.getVerticesSculptFlags();
var centerPoint = this.center_;
var xcen = centerPoint[0];
var ycen = centerPoint[1];
var zcen = centerPoint[2];
var vertexSculptMask = Utils.SCULPT_FLAG;
nbVNew = vNew.length;
for (i = 0; i < nbVNew; ++i) {
var ind = vNew[i];
var j = ind * 3;
var dx = vAr[j] - xcen;
var dy = vAr[j + 1] - ycen;
var dz = vAr[j + 2] - zcen;
vscf[ind] = (dx * dx + dy * dy + dz * dz) < this.radius2_ ? vertexSculptMask : vertexSculptMask - 1;
}
return iTrisMask;
},
/** Detect which triangles to split and the edge that need to be split */
initSplit: function (iTris) {
var nbTris = iTris.length;
var buffer = Utils.getMemory((4 + 1) * nbTris);
var iTrisSubd = new Uint32Array(buffer, 0, nbTris);
var split = new Uint8Array(buffer, 4 * nbTris, nbTris);
var acc = 0;
for (var i = 0; i < nbTris; ++i) {
var iTri = iTris[i];
var splitNum = this.findSplit(iTri, true);
if (splitNum === 0) continue;
split[acc] = splitNum;
iTrisSubd[acc++] = iTri;
}
return [new Uint32Array(iTrisSubd.subarray(0, acc)), new Uint8Array(split.subarray(0, acc))];
},
/** Find the edge to be split (0 otherwise) */
findSplit: (function () {
var v1 = [0.0, 0.0, 0.0];
var v2 = [0.0, 0.0, 0.0];
var v3 = [0.0, 0.0, 0.0];
var tis = Geometry.triangleInsideSphere;
var pit = Geometry.pointInsideTriangle;
return function (iTri, checkInsideSphere) {
var mesh = this.mesh_;
var vAr = mesh.getVertices();
var fAr = mesh.getFaces();
var id = iTri * 4;
var ind1 = fAr[id] * 3;
var ind2 = fAr[id + 1] * 3;
var ind3 = fAr[id + 2] * 3;
v1[0] = vAr[ind1];
v1[1] = vAr[ind1 + 1];
v1[2] = vAr[ind1 + 2];
v2[0] = vAr[ind2];
v2[1] = vAr[ind2 + 1];
v2[2] = vAr[ind2 + 2];
v3[0] = vAr[ind3];
v3[1] = vAr[ind3 + 1];
v3[2] = vAr[ind3 + 2];
if (checkInsideSphere && !tis(this.center_, this.radius2_, v1, v2, v3) && !pit(this.center_, v1, v2, v3))
return 0;
var length1 = vec3.sqrDist(v1, v2);
var length2 = vec3.sqrDist(v2, v3);
var length3 = vec3.sqrDist(v1, v3);
if (length1 > length2 && length1 > length3) return length1 > this.edgeMax2_ ? 1 : 0;
else if (length2 > length3) return length2 > this.edgeMax2_ ? 2 : 0;
else return length3 > this.edgeMax2_ ? 3 : 0;
};
})(),
/** Subdivide all the triangles that need to be subdivided */
subdivideTriangles: function (iTrisSubd, split) {
var fAr = this.mesh_.getFaces();
var nbTris = iTrisSubd.length;
for (var i = 0; i < nbTris; ++i) {
var iTri = iTrisSubd[i];
var splitNum = split[i];
if (splitNum === 0) splitNum = this.findSplit(iTri);
var ind = iTri * 4;
if (splitNum === 1) this.halfEdgeSplit(iTri, fAr[ind], fAr[ind + 1], fAr[ind + 2]);
else if (splitNum === 2) this.halfEdgeSplit(iTri, fAr[ind + 1], fAr[ind + 2], fAr[ind]);
else if (splitNum === 3) this.halfEdgeSplit(iTri, fAr[ind + 2], fAr[ind], fAr[ind + 1]);
}
},
/**
* Subdivide one triangle, it simply cut the triangle in two at a given edge.
* The position of the vertex is computed as follow :
* 1. Initial position of the new vertex at the middle of the edge
* 2. Compute normal of the new vertex (average of the two normals of the two vertices defining the edge)
* 3. Compute angle between those two normals
* 4. Move the new vertex along its normal with a strengh proportional to the angle computed at step 3.
*/
halfEdgeSplit: function (iTri, iv1, iv2, iv3) {
var mesh = this.mesh_;
var vAr = mesh.getVertices();
var nAr = mesh.getNormals();
var cAr = mesh.getColors();
var mAr = mesh.getMaterials();
var fAr = mesh.getFaces();
var pil = mesh.getFacePosInLeaf();
var fleaf = mesh.getFaceLeaf();
var vrv = mesh.getVerticesRingVert();
var vrf = mesh.getVerticesRingFace();
var fstf = mesh.getFacesStateFlags();
var vstf = mesh.getVerticesStateFlags();
var vMap = this.verticesMap_;
var key = Math.min(iv1, iv2) + '+' + Math.max(iv1, iv2);
var isNewVertex = false;
var ivMid = vMap.get(key);
if (ivMid === undefined) {
ivMid = mesh.getNbVertices();
isNewVertex = true;
vMap.set(key, ivMid);
}
vrv[iv3].push(ivMid);
var id = iTri * 4;
fAr[id] = iv1;
fAr[id + 1] = ivMid;
fAr[id + 2] = iv3;
fAr[id + 3] = -1;
var iNewTri = mesh.getNbTriangles();
id = iNewTri * 4;
fAr[id] = ivMid;
fAr[id + 1] = iv2;
fAr[id + 2] = iv3;
fAr[id + 3] = -1;
fstf[iNewTri] = Utils.STATE_FLAG;
vrf[iv3].push(iNewTri);
Utils.replaceElement(vrf[iv2], iTri, iNewTri);
var leaf = fleaf[iTri];
var iTrisLeaf = leaf.iFaces_;
fleaf[iNewTri] = leaf;
pil[iNewTri] = iTrisLeaf.length;
iTrisLeaf.push(iNewTri);
if (!isNewVertex) {
vrv[ivMid].push(iv3);
vrf[ivMid].push(iTri, iNewTri);
mesh.addNbFace(1);
return;
}
//new vertex
var iNewVer = mesh.getNbVertices();
var id1 = iv1 * 3;
var v1x = vAr[id1];
var v1y = vAr[id1 + 1];
var v1z = vAr[id1 + 2];
var n1x = nAr[id1];
var n1y = nAr[id1 + 1];
var n1z = nAr[id1 + 2];
var id2 = iv2 * 3;
var v2x = vAr[id2];
var v2y = vAr[id2 + 1];
var v2z = vAr[id2 + 2];
var n2x = nAr[id2];
var n2y = nAr[id2 + 1];
var n2z = nAr[id2 + 2];
var n1n2x = n1x + n2x;
var n1n2y = n1y + n2y;
var n1n2z = n1z + n2z;
var len = 1.0 / Math.sqrt(n1n2x * n1n2x + n1n2y * n1n2y + n1n2z * n1n2z);
id = iNewVer * 3;
nAr[id] = n1n2x = n1n2x * len;
nAr[id + 1] = n1n2y = n1n2y * len;
nAr[id + 2] = n1n2z = n1n2z * len;
cAr[id] = (cAr[id1] + cAr[id2]) * 0.5;
cAr[id + 1] = (cAr[id1 + 1] + cAr[id2 + 1]) * 0.5;
cAr[id + 2] = (cAr[id1 + 2] + cAr[id2 + 2]) * 0.5;
mAr[id] = (mAr[id1] + mAr[id2]) * 0.5;
mAr[id + 1] = (mAr[id1 + 1] + mAr[id2 + 1]) * 0.5;
mAr[id + 2] = (mAr[id1 + 2] + mAr[id2 + 2]) * 0.5;
var offset = 0;
if (this.linear_) {
vAr[id] = (v1x + v2x) * 0.5;
vAr[id + 1] = (v1y + v2y) * 0.5;
vAr[id + 2] = (v1z + v2z) * 0.5;
} else {
var dot = n1x * n2x + n1y * n2y + n1z * n2z;
var angle = 0;
if (dot <= -1) angle = Math.PI;
else if (dot >= 1) angle = 0;
else angle = Math.acos(dot);
var edgex = v1x - v2x;
var edgey = v1y - v2y;
var edgez = v1z - v2z;
len = Math.sqrt(edgex * edgex + edgey * edgey + edgez * edgez);
offset = angle * len * 0.02;
if ((edgex * (n1x - n2x) + edgey * (n1y - n2y) + edgez * (n1z - n2z)) < 0)
offset = -offset;
vAr[id] = (v1x + v2x) * 0.5 + n1n2x * offset;
vAr[id + 1] = (v1y + v2y) * 0.5 + n1n2y * offset;
vAr[id + 2] = (v1z + v2z) * 0.5 + n1n2z * offset;
}
vstf[iNewVer] = Utils.STATE_FLAG;
vrv[iNewVer] = [iv1, iv2, iv3];
vrf[iNewVer] = [iTri, iNewTri];
Utils.replaceElement(vrv[iv1], iv2, ivMid);
Utils.replaceElement(vrv[iv2], iv1, ivMid);
mesh.addNbVertice(1);
mesh.addNbFace(1);
},
/**
* Fill the triangles. It checks if a newly vertex has been created at the middle
* of the edge. If several split are needed, it first chooses the split that minimize
* the valence of the vertex.
*/
fillTriangles: function (iTris) {
var mesh = this.mesh_;
var vrv = mesh.getVerticesRingVert();
var fAr = mesh.getFaces();
var nbTris = iTris.length;
var iTrisNext = new Uint32Array(Utils.getMemory(4 * 2 * nbTris), 0, 2 * nbTris);
var nbNext = 0;
var vMap = this.verticesMap_;
for (var i = 0; i < nbTris; ++i) {
var iTri = iTris[i];
var j = iTri * 4;
var iv1 = fAr[j];
var iv2 = fAr[j + 1];
var iv3 = fAr[j + 2];
var val1 = vMap.get(Math.min(iv1, iv2) + '+' + Math.max(iv1, iv2));
var val2 = vMap.get(Math.min(iv2, iv3) + '+' + Math.max(iv2, iv3));
var val3 = vMap.get(Math.min(iv1, iv3) + '+' + Math.max(iv1, iv3));
var num1 = vrv[iv1].length;
var num2 = vrv[iv2].length;
var num3 = vrv[iv3].length;
var split = 0;
if (val1) {
if (val2) {
if (val3) {
if (num1 < num2 && num1 < num3) split = 2;
else if (num2 < num3) split = 3;
else split = 1;
} else if (num1 < num3) split = 2;
else split = 1;
} else if (val3 && num2 < num3) split = 3;
else split = 1;
} else if (val2) {
if (val3 && num2 < num1) split = 3;
else split = 2;
} else if (val3) split = 3;
if (split === 1) this.fillTriangle(iTri, iv1, iv2, iv3, val1);
else if (split === 2) this.fillTriangle(iTri, iv2, iv3, iv1, val2);
else if (split === 3) this.fillTriangle(iTri, iv3, iv1, iv2, val3);
else continue;
iTrisNext[nbNext++] = iTri;
iTrisNext[nbNext++] = mesh.getNbTriangles() - 1;
}
return new Uint32Array(iTrisNext.subarray(0, nbNext));
},
/** Fill crack on one triangle */
fillTriangle: function (iTri, iv1, iv2, iv3, ivMid) {
var mesh = this.mesh_;
var vrv = mesh.getVerticesRingVert();
var vrf = mesh.getVerticesRingFace();
var pil = mesh.getFacePosInLeaf();
var fleaf = mesh.getFaceLeaf();
var fstf = mesh.getFacesStateFlags();
var fAr = mesh.getFaces();
var j = iTri * 4;
fAr[j] = iv1;
fAr[j + 1] = ivMid;
fAr[j + 2] = iv3;
fAr[j + 3] = -1;
var leaf = fleaf[iTri];
var iTrisLeaf = leaf.iFaces_;
vrv[ivMid].push(iv3);
vrv[iv3].push(ivMid);
var iNewTri = mesh.getNbTriangles();
vrf[ivMid].push(iTri, iNewTri);
j = iNewTri * 4;
fAr[j] = ivMid;
fAr[j + 1] = iv2;
fAr[j + 2] = iv3;
fAr[j + 3] = -1;
fstf[iNewTri] = Utils.STATE_FLAG;
fleaf[iNewTri] = leaf;
pil[iNewTri] = iTrisLeaf.length;
vrf[iv3].push(iNewTri);
Utils.replaceElement(vrf[iv2], iTri, iNewTri);
iTrisLeaf.push(iNewTri);
mesh.addNbFace(1);
}
};
return Subdivision;
}); | Fixes non linear subdivision vertex computation
| src/mesh/dynamic/Subdivision.js | Fixes non linear subdivision vertex computation | <ide><path>rc/mesh/dynamic/Subdivision.js
<ide> var n1n2x = n1x + n2x;
<ide> var n1n2y = n1y + n2y;
<ide> var n1n2z = n1z + n2z;
<del> var len = 1.0 / Math.sqrt(n1n2x * n1n2x + n1n2y * n1n2y + n1n2z * n1n2z);
<ide> id = iNewVer * 3;
<del> nAr[id] = n1n2x = n1n2x * len;
<del> nAr[id + 1] = n1n2y = n1n2y * len;
<del> nAr[id + 2] = n1n2z = n1n2z * len;
<add> nAr[id] = n1n2x * 0.5;
<add> nAr[id + 1] = n1n2y * 0.5;
<add> nAr[id + 2] = n1n2z * 0.5;
<ide> cAr[id] = (cAr[id1] + cAr[id2]) * 0.5;
<ide> cAr[id + 1] = (cAr[id1 + 1] + cAr[id2 + 1]) * 0.5;
<ide> cAr[id + 2] = (cAr[id1 + 2] + cAr[id2 + 2]) * 0.5;
<ide> vAr[id + 1] = (v1y + v2y) * 0.5;
<ide> vAr[id + 2] = (v1z + v2z) * 0.5;
<ide> } else {
<add> var len = 1.0 / Math.sqrt(n1x * n1x + n1y * n1y + n1z * n1z);
<add> n1x *= len;
<add> n1y *= len;
<add> n1z *= len;
<add> len = 1.0 / Math.sqrt(n2x * n2x + n2y * n2y + n2z * n2z);
<add> n2x *= len;
<add> n2y *= len;
<add> n2z *= len;
<ide> var dot = n1x * n2x + n1y * n2y + n1z * n2z;
<ide> var angle = 0;
<ide> if (dot <= -1) angle = Math.PI;
<ide> var edgex = v1x - v2x;
<ide> var edgey = v1y - v2y;
<ide> var edgez = v1z - v2z;
<del> len = Math.sqrt(edgex * edgex + edgey * edgey + edgez * edgez);
<del> offset = angle * len * 0.02;
<add> offset = angle * 0.12;
<add> offset *= Math.sqrt(edgex * edgex + edgey * edgey + edgez * edgez);
<add> offset /= Math.sqrt(n1n2x * n1n2x + n1n2y * n1n2y + n1n2z * n1n2z);
<ide> if ((edgex * (n1x - n2x) + edgey * (n1y - n2y) + edgez * (n1z - n2z)) < 0)
<ide> offset = -offset;
<ide> vAr[id] = (v1x + v2x) * 0.5 + n1n2x * offset; |
|
Java | mit | 68908fa9c815242d31f0cf1f8b1dde94ad47a012 | 0 | restfb/restfb | /*
* Copyright (c) 2010-2015 Mark Allen.
*
* 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.restfb.types;
import static java.util.Collections.unmodifiableList;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.restfb.Facebook;
import com.restfb.JsonMapper.JsonMappingCompleted;
import static com.restfb.util.DateUtils.toDateFromLongFormat;
import lombok.Getter;
import lombok.Setter;
/**
* Represents the <a href="http://developers.facebook.com/docs/reference/api/video">Video Graph API type</a>.
*
* @author <a href="http://restfb.com">Mark Allen</a>
* @since 1.5
*/
public class Video extends NamedFacebookType {
/**
* An object containing the name and ID of the user who posted the video.
*
* @return An object containing the name and ID of the user who posted the video.
*/
@Getter
@Setter
@Facebook
private CategorizedFacebookType from;
/**
* The video title / caption.
*
* @return The video title / caption.
* @deprecated FB seems to have removed this field.
*/
@Getter
@Setter
@Facebook
@Deprecated
private String message;
/**
* The long-form HTML description of the video.
*
* @return The long-form HTML description of the video.
*/
@Getter
@Setter
@Facebook
private String description;
/**
* A picture URL which represents the video.
*
* @return A picture URL which represents the video.
*/
@Getter
@Setter
@Facebook
private String picture;
/**
* An icon URL which represents the video.
*
* @return An icon URL which represents the video.
*/
@Getter
@Setter
@Facebook
private String icon;
/**
* A URL to the raw, playable video file.
*
* @return A URL to the raw, playable video file.
* @since 1.6.5
*/
@Getter
@Setter
@Facebook
private String source;
/**
* HTML that may be used to embed the video on another website.
*
* @return HTML that may be used to embed the video on another website.
*/
@Getter
@Setter
@Facebook("embed_html")
private String embedHtml;
/**
* The length of the video, in seconds.
*
* @return The length of the video, in seconds.
*/
@Getter
@Setter
@Facebook
private Integer length;
/**
* Whether a post about this video is published.
*
* This field is only accessible in Graph API 2.3 or later.
*
* @return whether a post about this video is published.
* @since 1.10.0
*/
@Getter
@Setter
@Facebook
private Boolean published;
@Facebook("created_time")
private String rawCreatedTime;
@Facebook("updated_time")
private String rawUpdatedTime;
@Facebook("scheduled_publish_time")
private String rawScheduledPublishTime;
/**
* The time the video was initially published.
*
* @return The time the video was initially published.
*/
@Getter
@Setter
private Date createdTime;
/**
* The last time the video or its caption were updated.
*
* @return The last time the video or its caption were updated.
*/
@Getter
@Setter
private Date updatedTime;
/**
* The time that the video is scheduled to expire.
*
* This field is only accessible in Graph API 2.3 or later.
*
* @return The time that the video is scheduled to expire.
* @since 1.10.0
*/
@Getter
@Setter
private Date scheduledPublishTime;
@Facebook
private List<NamedFacebookType> tags = new ArrayList<NamedFacebookType>();
@Facebook
private List<Comment> comments = new ArrayList<Comment>();
private static final long serialVersionUID = 1L;
/**
* Tags for the video.
*
* @return Tags for the video.
* @since 1.6.5
*/
public List<NamedFacebookType> getTags() {
return unmodifiableList(tags);
}
public boolean addTag(NamedFacebookType tag) {
return tags.add(tag);
}
public boolean removeTag(NamedFacebookType tag) {
return tags.remove(tag);
}
/**
* Comments for the video.
*
* @return Comments for the video.
*/
public List<Comment> getComments() {
return unmodifiableList(comments);
}
public boolean addComment(Comment comment) {
return comments.add(comment);
}
public boolean removeComment(Comment comment) {
return comments.remove(comment);
}
@JsonMappingCompleted
void convertTime() {
createdTime = toDateFromLongFormat(rawCreatedTime);
updatedTime = toDateFromLongFormat(rawUpdatedTime);
scheduledPublishTime = toDateFromLongFormat(rawScheduledPublishTime);
}
} | source/library/com/restfb/types/Video.java | /*
* Copyright (c) 2010-2015 Mark Allen.
*
* 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.restfb.types;
import static java.util.Collections.unmodifiableList;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.restfb.Facebook;
import com.restfb.JsonMapper.JsonMappingCompleted;
import static com.restfb.util.DateUtils.toDateFromLongFormat;
import lombok.Getter;
import lombok.Setter;
/**
* Represents the <a href="http://developers.facebook.com/docs/reference/api/video">Video Graph API type</a>.
*
* @author <a href="http://restfb.com">Mark Allen</a>
* @since 1.5
*/
public class Video extends NamedFacebookType {
/**
* An object containing the name and ID of the user who posted the video.
*
* @return An object containing the name and ID of the user who posted the video.
*/
@Getter
@Setter
@Facebook
private CategorizedFacebookType from;
/**
* The video title / caption.
*
* @return The video title / caption.
* @deprecated FB seems to have removed this field.
*/
@Getter
@Setter
@Facebook
@Deprecated
private String message;
/**
* The long-form HTML description of the video.
*
* @return The long-form HTML description of the video.
*/
@Getter
@Setter
@Facebook
private String description;
/**
* A picture URL which represents the video.
*
* @return A picture URL which represents the video.
*/
@Getter
@Setter
@Facebook
private String picture;
/**
* An icon URL which represents the video.
*
* @return An icon URL which represents the video.
*/
@Getter
@Setter
@Facebook
private String icon;
/**
* A URL to the raw, playable video file.
*
* @return A URL to the raw, playable video file.
* @since 1.6.5
*/
@Getter
@Setter
@Facebook
private String source;
/**
* HTML that may be used to embed the video on another website.
*
* @return HTML that may be used to embed the video on another website.
*/
@Getter
@Setter
@Facebook("embed_html")
private String embedHtml;
/**
* The length of the video, in seconds.
*
* @return The length of the video, in seconds.
*/
@Getter
@Setter
@Facebook
private Integer length;
@Facebook("created_time")
private String rawCreatedTime;
@Facebook("updated_time")
private String rawUpdatedTime;
/**
* The time the video was initially published.
*
* @return The time the video was initially published.
*/
@Getter
@Setter
private Date createdTime;
/**
* The last time the video or its caption were updated.
*
* @return The last time the video or its caption were updated.
*/
@Getter
@Setter
private Date updatedTime;
@Facebook
private List<NamedFacebookType> tags = new ArrayList<NamedFacebookType>();
@Facebook
private List<Comment> comments = new ArrayList<Comment>();
private static final long serialVersionUID = 1L;
/**
* Tags for the video.
*
* @return Tags for the video.
* @since 1.6.5
*/
public List<NamedFacebookType> getTags() {
return unmodifiableList(tags);
}
public boolean addTag(NamedFacebookType tag) {
return tags.add(tag);
}
public boolean removeTag(NamedFacebookType tag) {
return tags.remove(tag);
}
/**
* Comments for the video.
*
* @return Comments for the video.
*/
public List<Comment> getComments() {
return unmodifiableList(comments);
}
public boolean addComment(Comment comment) {
return comments.add(comment);
}
public boolean removeComment(Comment comment) {
return comments.remove(comment);
}
@JsonMappingCompleted
void convertTime() {
createdTime = toDateFromLongFormat(rawCreatedTime);
updatedTime = toDateFromLongFormat(rawUpdatedTime);
}
} | Issue #209 - published field and scheduled_publish_time field added
| source/library/com/restfb/types/Video.java | Issue #209 - published field and scheduled_publish_time field added | <ide><path>ource/library/com/restfb/types/Video.java
<ide> @Facebook
<ide> private Integer length;
<ide>
<add> /**
<add> * Whether a post about this video is published.
<add> *
<add> * This field is only accessible in Graph API 2.3 or later.
<add> *
<add> * @return whether a post about this video is published.
<add> * @since 1.10.0
<add> */
<add> @Getter
<add> @Setter
<add> @Facebook
<add> private Boolean published;
<add>
<ide> @Facebook("created_time")
<ide> private String rawCreatedTime;
<ide>
<ide> @Facebook("updated_time")
<ide> private String rawUpdatedTime;
<ide>
<add> @Facebook("scheduled_publish_time")
<add> private String rawScheduledPublishTime;
<add>
<ide> /**
<ide> * The time the video was initially published.
<ide> *
<ide> @Getter
<ide> @Setter
<ide> private Date updatedTime;
<add>
<add> /**
<add> * The time that the video is scheduled to expire.
<add> *
<add> * This field is only accessible in Graph API 2.3 or later.
<add> *
<add> * @return The time that the video is scheduled to expire.
<add> * @since 1.10.0
<add> */
<add> @Getter
<add> @Setter
<add> private Date scheduledPublishTime;
<ide>
<ide> @Facebook
<ide> private List<NamedFacebookType> tags = new ArrayList<NamedFacebookType>();
<ide> void convertTime() {
<ide> createdTime = toDateFromLongFormat(rawCreatedTime);
<ide> updatedTime = toDateFromLongFormat(rawUpdatedTime);
<add> scheduledPublishTime = toDateFromLongFormat(rawScheduledPublishTime);
<ide> }
<ide> } |
|
Java | mit | 1c46299abd0d38bb2f69d02ae4f323d857f1d6d6 | 0 | nongfenqi/nexus3-rundeck-plugin,nongfenqi/nexus3-rundeck-plugin | package com.nongfenqi.nexus.plugin.rundeck;
import com.google.common.base.Supplier;
import org.apache.http.client.utils.DateUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.sonatype.goodies.common.ComponentSupport;
import org.sonatype.nexus.blobstore.api.Blob;
import org.sonatype.nexus.repository.Repository;
import org.sonatype.nexus.repository.manager.RepositoryManager;
import org.sonatype.nexus.repository.search.SearchService;
import org.sonatype.nexus.repository.storage.Asset;
import org.sonatype.nexus.repository.storage.Bucket;
import org.sonatype.nexus.repository.storage.StorageFacet;
import org.sonatype.nexus.repository.storage.StorageTx;
import org.sonatype.nexus.rest.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.*;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.sonatype.nexus.common.text.Strings2.isBlank;
@Named
@Singleton
@Path("/rundeck/maven/options")
public class RundeckMavenResource extends ComponentSupport implements Resource {
private final SearchService searchService;
private final RepositoryManager repositoryManager;
private static final Response NOT_FOUND = Response.status(404).build();
@Inject
public RundeckMavenResource(
SearchService searchService,
RepositoryManager repositoryManager
) {
this.searchService = checkNotNull(searchService);
this.repositoryManager = checkNotNull(repositoryManager);
}
@GET
@Path("content")
public Response content(
@QueryParam("r") String repositoryName,
@QueryParam("g") String groupId,
@QueryParam("a") String artifactId,
@QueryParam("v") String version
) {
if (isBlank(repositoryName) || isBlank(groupId) || isBlank(artifactId) || isBlank(version)) {
return NOT_FOUND;
}
Repository repository = repositoryManager.get(repositoryName);
if (null == repository || !repository.getFormat().getValue().equals("maven2")) {
return NOT_FOUND;
}
StorageFacet facet = repository.facet(StorageFacet.class);
Supplier<StorageTx> storageTxSupplier = facet.txSupplier();
log.debug("rundeck download repository: {}", repository);
final StorageTx tx = storageTxSupplier.get();
tx.begin();
Bucket bucket = tx.findBucket(repository);
log.debug("rundeck download bucket: {}", bucket);
if (null == bucket) {
return commitAndReturn(NOT_FOUND, tx);
}
String path = groupId.replace(".", "/") + "/" + artifactId + "/" + version + "/" + artifactId + "-" + version + ".jar";
Asset asset = tx.findAssetWithProperty("name", path, bucket);
log.debug("rundeck download asset: {}", asset);
if (null == asset) {
return commitAndReturn(NOT_FOUND, tx);
}
asset.markAsDownloaded();
tx.saveAsset(asset);
Blob blob = tx.requireBlob(asset.requireBlobRef());
Response.ResponseBuilder ok = Response.ok(blob.getInputStream());
ok.header("Content-Type", blob.getHeaders().get("BlobStore.content-type"));
ok.header("Content-Disposition", "attachment;filename=\"" + path.substring(path.lastIndexOf("/")) + "\"");
return commitAndReturn(ok.build(), tx);
}
@GET
@Path("version")
@Produces(APPLICATION_JSON)
public List<RundeckXO> version(
@DefaultValue("10") @QueryParam("l") int limit,
@QueryParam("r") String repository,
@QueryParam("g") String groupId,
@QueryParam("a") String artifactId,
@QueryParam("c") String classifier,
@QueryParam("p") String extension
) {
log.debug("param value, repository: {}, limit: {}, groupId: {}, artifactId: {}, classifier: {}, extension: {}", repository, limit, groupId, artifactId, classifier, extension);
BoolQueryBuilder query = boolQuery();
query.filter(termQuery("format", "maven2"));
if (!isBlank(repository)) {
query.filter(termQuery("repository_name", repository));
}
if (!isBlank(groupId)) {
query.filter(termQuery("attributes.maven2.groupId", groupId));
}
if (!isBlank(artifactId)) {
query.filter(termQuery("attributes.maven2.artifactId", artifactId));
}
if (!isBlank(classifier)) {
query.filter(termQuery("assets.attributes.maven2.classifier", classifier));
}
if (!isBlank(extension)) {
query.filter(termQuery("assets.attributes.maven2.extension", extension));
}
log.debug("rundeck maven version query: {}", query);
SearchResponse result = searchService.search(
query,
Collections.singletonList(new FieldSortBuilder("assets.attributes.content.last_modified").order(SortOrder.DESC)),
0,
limit
);
return Arrays.stream(result.getHits().hits())
.map(this::his2RundeckXO)
.collect(Collectors.toList());
}
private RundeckXO his2RundeckXO(SearchHit hit) {
String version = (String) hit.getSource().get("version");
List<Map<String, Object>> assets = (List<Map<String, Object>>) hit.getSource().get("assets");
Map<String, Object> attributes = (Map<String, Object>) assets.get(0).get("attributes");
Map<String, Object> content = (Map<String, Object>) attributes.get("content");
long lastModified = (long) content.get("last_modified");
String lastModifiedTime = DateUtils.formatDate(new Date(lastModified), "yyyy-MM-dd HH:mm:ss");
return RundeckXO.builder().name(version + " (" + lastModifiedTime + ")").value(version).build();
}
private Response commitAndReturn(Response response, StorageTx tx) {
if (tx.isActive()) {
tx.commit();
}
return response;
}
}
| src/main/java/com/nongfenqi/nexus/plugin/rundeck/RundeckMavenResource.java | package com.nongfenqi.nexus.plugin.rundeck;
import com.google.common.base.Supplier;
import org.apache.http.client.utils.DateUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.sonatype.goodies.common.ComponentSupport;
import org.sonatype.nexus.blobstore.api.Blob;
import org.sonatype.nexus.repository.Repository;
import org.sonatype.nexus.repository.manager.RepositoryManager;
import org.sonatype.nexus.repository.search.SearchService;
import org.sonatype.nexus.repository.storage.Asset;
import org.sonatype.nexus.repository.storage.Bucket;
import org.sonatype.nexus.repository.storage.StorageFacet;
import org.sonatype.nexus.repository.storage.StorageTx;
import org.sonatype.nexus.rest.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.*;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.sonatype.nexus.common.text.Strings2.isBlank;
@Named
@Singleton
@Path("/rundeck/maven/options")
public class RundeckMavenResource extends ComponentSupport implements Resource {
private final SearchService searchService;
private final RepositoryManager repositoryManager;
private static final Response NOT_FOUND = Response.status(404).build();
@Inject
public RundeckMavenResource(
SearchService searchService,
RepositoryManager repositoryManager
) {
this.searchService = checkNotNull(searchService);
this.repositoryManager = checkNotNull(repositoryManager);
}
@GET
@Path("content")
public Response content(
@QueryParam("r") String repositoryName,
@QueryParam("g") String groupId,
@QueryParam("a") String artifactId,
@QueryParam("v") String version
) {
if (isBlank(repositoryName) || isBlank(groupId) || isBlank(artifactId) || isBlank(version)) {
return NOT_FOUND;
}
Repository repository = repositoryManager.get(repositoryName);
if (null == repository || !repository.getFormat().getValue().equals("maven2")) {
return NOT_FOUND;
}
StorageFacet facet = repository.facet(StorageFacet.class);
Supplier<StorageTx> storageTxSupplier = facet.txSupplier();
log.debug("rundeck download repository: {}", repository);
final StorageTx tx = storageTxSupplier.get();
tx.begin();
Bucket bucket = tx.findBucket(repository);
log.debug("rundeck download bucket: {}", bucket);
if (null == bucket) {
return commitAndReturn(NOT_FOUND, tx);
}
String path = groupId.replace(".", "/") + "/" + artifactId + "/" + version + "/" + artifactId + "-" + version + ".jar";
Asset asset = tx.findAssetWithProperty("name", path, bucket);
log.debug("rundeck download asset: {}", asset);
if (null == asset) {
return commitAndReturn(NOT_FOUND, tx);
}
asset.markAsDownloaded();
tx.saveAsset(asset);
Blob blob = tx.requireBlob(asset.requireBlobRef());
Response.ResponseBuilder ok = Response.ok(blob.getInputStream());
ok.header("Content-Type", blob.getHeaders().get("BlobStore.content-type"));
ok.header("Content-Disposition", "attachment;filename=\"" + path.substring(path.lastIndexOf("/")) + "\"");
return commitAndReturn(ok.build(), tx);
}
@GET
@Path("version")
@Produces(APPLICATION_JSON)
public List<RundeckXO> version(
@DefaultValue("10") @QueryParam("step") int limit,
@QueryParam("r") String repository,
@QueryParam("g") String groupId,
@QueryParam("a") String artifactId,
@QueryParam("c") String classifier,
@QueryParam("p") String extension
) {
log.debug("param value, repository: {}, limit: {}, groupId: {}, artifactId: {}, classifier: {}, extension: {}", repository, limit, groupId, artifactId, classifier, extension);
BoolQueryBuilder query = boolQuery();
query.filter(termQuery("format", "maven2"));
if (!isBlank(repository)) {
query.filter(termQuery("repository_name", groupId));
}
if (!isBlank(groupId)) {
query.filter(termQuery("attributes.maven2.groupId", groupId));
}
if (!isBlank(artifactId)) {
query.filter(termQuery("attributes.maven2.artifactId", artifactId));
}
if (!isBlank(classifier)) {
query.filter(termQuery("assets.attributes.maven2.classifier", classifier));
}
if (!isBlank(extension)) {
query.filter(termQuery("assets.attributes.maven2.extension", extension));
}
log.debug("rundeck maven version query: {}", query);
SearchResponse result = searchService.search(
query,
Collections.singletonList(new FieldSortBuilder("assets.attributes.content.last_modified").order(SortOrder.DESC)),
0,
limit
);
return Arrays.stream(result.getHits().hits())
.map(this::his2RundeckXO)
.collect(Collectors.toList());
}
private RundeckXO his2RundeckXO(SearchHit hit) {
String version = (String) hit.getSource().get("version");
List<Map<String, Object>> assets = (List<Map<String, Object>>) hit.getSource().get("assets");
Map<String, Object> attributes = (Map<String, Object>) assets.get(0).get("attributes");
Map<String, Object> content = (Map<String, Object>) attributes.get("content");
long lastModified = (long) content.get("last_modified");
String lastModifiedTime = DateUtils.formatDate(new Date(lastModified), "yyyy-MM-dd HH:mm:ss");
return RundeckXO.builder().name(version + " (" + lastModifiedTime + ")").value(version).build();
}
private Response commitAndReturn(Response response, StorageTx tx) {
if (tx.isActive()) {
tx.commit();
}
return response;
}
}
| version bug
| src/main/java/com/nongfenqi/nexus/plugin/rundeck/RundeckMavenResource.java | version bug | <ide><path>rc/main/java/com/nongfenqi/nexus/plugin/rundeck/RundeckMavenResource.java
<ide> @Path("version")
<ide> @Produces(APPLICATION_JSON)
<ide> public List<RundeckXO> version(
<del> @DefaultValue("10") @QueryParam("step") int limit,
<add> @DefaultValue("10") @QueryParam("l") int limit,
<ide> @QueryParam("r") String repository,
<ide> @QueryParam("g") String groupId,
<ide> @QueryParam("a") String artifactId,
<ide> query.filter(termQuery("format", "maven2"));
<ide>
<ide> if (!isBlank(repository)) {
<del> query.filter(termQuery("repository_name", groupId));
<add> query.filter(termQuery("repository_name", repository));
<ide> }
<ide> if (!isBlank(groupId)) {
<ide> query.filter(termQuery("attributes.maven2.groupId", groupId)); |
|
Java | agpl-3.0 | 4b11bdb7b292547d0424eba245dc4f67475901ea | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 5bd386ec-2e61-11e5-9284-b827eb9e62be | hello.java | 5bce0442-2e61-11e5-9284-b827eb9e62be | 5bd386ec-2e61-11e5-9284-b827eb9e62be | hello.java | 5bd386ec-2e61-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>5bce0442-2e61-11e5-9284-b827eb9e62be
<add>5bd386ec-2e61-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 6f0ea0cddf1bbc64c10fc6c7598cd320e46a5063 | 0 | SeleniumHQ/buck,clonetwin26/buck,zhan-xiong/buck,Addepar/buck,k21/buck,romanoid/buck,shs96c/buck,shs96c/buck,LegNeato/buck,LegNeato/buck,dsyang/buck,shybovycha/buck,LegNeato/buck,dsyang/buck,dsyang/buck,nguyentruongtho/buck,marcinkwiatkowski/buck,shybovycha/buck,zhan-xiong/buck,clonetwin26/buck,brettwooldridge/buck,SeleniumHQ/buck,shybovycha/buck,zhan-xiong/buck,SeleniumHQ/buck,robbertvanginkel/buck,LegNeato/buck,k21/buck,zhan-xiong/buck,clonetwin26/buck,SeleniumHQ/buck,brettwooldridge/buck,JoelMarcey/buck,nguyentruongtho/buck,SeleniumHQ/buck,shs96c/buck,zhan-xiong/buck,shybovycha/buck,dsyang/buck,Addepar/buck,clonetwin26/buck,shs96c/buck,clonetwin26/buck,marcinkwiatkowski/buck,LegNeato/buck,k21/buck,robbertvanginkel/buck,SeleniumHQ/buck,marcinkwiatkowski/buck,Addepar/buck,robbertvanginkel/buck,rmaz/buck,facebook/buck,zhan-xiong/buck,nguyentruongtho/buck,k21/buck,k21/buck,JoelMarcey/buck,facebook/buck,LegNeato/buck,robbertvanginkel/buck,Addepar/buck,robbertvanginkel/buck,robbertvanginkel/buck,shs96c/buck,nguyentruongtho/buck,zpao/buck,JoelMarcey/buck,romanoid/buck,facebook/buck,shybovycha/buck,zpao/buck,romanoid/buck,facebook/buck,robbertvanginkel/buck,LegNeato/buck,brettwooldridge/buck,romanoid/buck,rmaz/buck,dsyang/buck,robbertvanginkel/buck,dsyang/buck,JoelMarcey/buck,clonetwin26/buck,romanoid/buck,ilya-klyuchnikov/buck,marcinkwiatkowski/buck,dsyang/buck,shybovycha/buck,zhan-xiong/buck,zpao/buck,clonetwin26/buck,Addepar/buck,facebook/buck,brettwooldridge/buck,Addepar/buck,JoelMarcey/buck,romanoid/buck,ilya-klyuchnikov/buck,shybovycha/buck,LegNeato/buck,rmaz/buck,marcinkwiatkowski/buck,ilya-klyuchnikov/buck,rmaz/buck,rmaz/buck,robbertvanginkel/buck,zpao/buck,zhan-xiong/buck,nguyentruongtho/buck,nguyentruongtho/buck,SeleniumHQ/buck,zhan-xiong/buck,brettwooldridge/buck,shybovycha/buck,ilya-klyuchnikov/buck,Addepar/buck,kageiit/buck,shybovycha/buck,clonetwin26/buck,JoelMarcey/buck,Addepar/buck,SeleniumHQ/buck,dsyang/buck,marcinkwiatkowski/buck,robbertvanginkel/buck,LegNeato/buck,marcinkwiatkowski/buck,JoelMarcey/buck,shybovycha/buck,k21/buck,zhan-xiong/buck,shs96c/buck,Addepar/buck,brettwooldridge/buck,zhan-xiong/buck,rmaz/buck,dsyang/buck,zhan-xiong/buck,ilya-klyuchnikov/buck,zhan-xiong/buck,marcinkwiatkowski/buck,shs96c/buck,clonetwin26/buck,k21/buck,LegNeato/buck,ilya-klyuchnikov/buck,kageiit/buck,k21/buck,k21/buck,brettwooldridge/buck,SeleniumHQ/buck,zpao/buck,facebook/buck,dsyang/buck,ilya-klyuchnikov/buck,romanoid/buck,shs96c/buck,ilya-klyuchnikov/buck,JoelMarcey/buck,dsyang/buck,marcinkwiatkowski/buck,robbertvanginkel/buck,LegNeato/buck,JoelMarcey/buck,clonetwin26/buck,clonetwin26/buck,zpao/buck,JoelMarcey/buck,shs96c/buck,robbertvanginkel/buck,shs96c/buck,brettwooldridge/buck,shybovycha/buck,JoelMarcey/buck,LegNeato/buck,marcinkwiatkowski/buck,k21/buck,brettwooldridge/buck,brettwooldridge/buck,rmaz/buck,clonetwin26/buck,romanoid/buck,SeleniumHQ/buck,ilya-klyuchnikov/buck,marcinkwiatkowski/buck,k21/buck,nguyentruongtho/buck,ilya-klyuchnikov/buck,shs96c/buck,kageiit/buck,ilya-klyuchnikov/buck,Addepar/buck,clonetwin26/buck,marcinkwiatkowski/buck,brettwooldridge/buck,LegNeato/buck,Addepar/buck,k21/buck,zpao/buck,brettwooldridge/buck,romanoid/buck,Addepar/buck,shs96c/buck,rmaz/buck,JoelMarcey/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,shs96c/buck,Addepar/buck,shybovycha/buck,rmaz/buck,dsyang/buck,rmaz/buck,JoelMarcey/buck,romanoid/buck,rmaz/buck,kageiit/buck,k21/buck,kageiit/buck,shybovycha/buck,marcinkwiatkowski/buck,ilya-klyuchnikov/buck,romanoid/buck,romanoid/buck,dsyang/buck,SeleniumHQ/buck,romanoid/buck,facebook/buck,rmaz/buck,SeleniumHQ/buck,brettwooldridge/buck,kageiit/buck,robbertvanginkel/buck,rmaz/buck,kageiit/buck | /*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cxx;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.json.JsonConcatenate;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.FlavorDomain;
import com.facebook.buck.model.InternalFlavor;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.CommandTool;
import com.facebook.buck.rules.RuleKeyObjectSink;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.SourceWithFlags;
import com.facebook.buck.rules.SymlinkTree;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.FileListableLinkerInputArg;
import com.facebook.buck.rules.args.RuleKeyAppendableFunction;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.rules.args.StringWithMacrosArg;
import com.facebook.buck.rules.coercer.FrameworkPath;
import com.facebook.buck.rules.coercer.PatternMatchedCollection;
import com.facebook.buck.rules.coercer.SourceList;
import com.facebook.buck.rules.macros.LocationMacroExpander;
import com.facebook.buck.rules.macros.MacroHandler;
import com.facebook.buck.rules.macros.StringWithMacros;
import com.facebook.buck.rules.query.QueryUtils;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.MoreCollectors;
import com.facebook.buck.util.RichStream;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.io.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.SortedSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.StreamSupport;
public class CxxDescriptionEnhancer {
private static final Logger LOG = Logger.get(CxxDescriptionEnhancer.class);
public static final Flavor SANDBOX_TREE_FLAVOR = InternalFlavor.of("sandbox");
public static final Flavor HEADER_SYMLINK_TREE_FLAVOR = InternalFlavor.of("private-headers");
public static final Flavor EXPORTED_HEADER_SYMLINK_TREE_FLAVOR = InternalFlavor.of("headers");
public static final Flavor STATIC_FLAVOR = InternalFlavor.of("static");
public static final Flavor STATIC_PIC_FLAVOR = InternalFlavor.of("static-pic");
public static final Flavor SHARED_FLAVOR = InternalFlavor.of("shared");
public static final Flavor MACH_O_BUNDLE_FLAVOR = InternalFlavor.of("mach-o-bundle");
public static final Flavor SHARED_LIBRARY_SYMLINK_TREE_FLAVOR =
InternalFlavor.of("shared-library-symlink-tree");
public static final Flavor CXX_LINK_BINARY_FLAVOR = InternalFlavor.of("binary");
protected static final MacroHandler MACRO_HANDLER =
new MacroHandler(ImmutableMap.of("location", new LocationMacroExpander()));
private static final Pattern SONAME_EXT_MACRO_PATTERN =
Pattern.compile("\\$\\(ext(?: ([.0-9]+))?\\)");
private CxxDescriptionEnhancer() {}
public static CxxPreprocessables.HeaderMode getHeaderModeForPlatform(
BuildRuleResolver resolver, CxxPlatform cxxPlatform, boolean shouldCreateHeadersSymlinks) {
boolean useHeaderMap =
(cxxPlatform.getCpp().resolve(resolver).supportsHeaderMaps()
&& cxxPlatform.getCxxpp().resolve(resolver).supportsHeaderMaps());
return !useHeaderMap
? CxxPreprocessables.HeaderMode.SYMLINK_TREE_ONLY
: (shouldCreateHeadersSymlinks
? CxxPreprocessables.HeaderMode.SYMLINK_TREE_WITH_HEADER_MAP
: CxxPreprocessables.HeaderMode.HEADER_MAP_ONLY);
}
public static HeaderSymlinkTree createHeaderSymlinkTree(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleResolver resolver,
CxxPreprocessables.HeaderMode mode,
ImmutableMap<Path, SourcePath> headers,
HeaderVisibility headerVisibility,
Flavor... flavors) {
BuildTarget headerSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
buildTarget, headerVisibility, flavors);
Path headerSymlinkTreeRoot =
CxxDescriptionEnhancer.getHeaderSymlinkTreePath(
projectFilesystem, buildTarget, headerVisibility, flavors);
return CxxPreprocessables.createHeaderSymlinkTreeBuildRule(
headerSymlinkTreeTarget,
projectFilesystem,
headerSymlinkTreeRoot,
headers,
mode,
new SourcePathRuleFinder(resolver));
}
public static HeaderSymlinkTree createHeaderSymlinkTree(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleResolver resolver,
CxxPlatform cxxPlatform,
ImmutableMap<Path, SourcePath> headers,
HeaderVisibility headerVisibility,
boolean shouldCreateHeadersSymlinks) {
return createHeaderSymlinkTree(
buildTarget,
projectFilesystem,
resolver,
getHeaderModeForPlatform(resolver, cxxPlatform, shouldCreateHeadersSymlinks),
headers,
headerVisibility,
cxxPlatform.getFlavor());
}
public static SymlinkTree createSandboxSymlinkTree(
BuildRuleParams params,
CxxPlatform cxxPlatform,
ImmutableMap<Path, SourcePath> map,
SourcePathRuleFinder ruleFinder) {
BuildTarget sandboxSymlinkTreeTarget =
CxxDescriptionEnhancer.createSandboxSymlinkTreeTarget(
params.getBuildTarget(), cxxPlatform.getFlavor());
Path sandboxSymlinkTreeRoot =
CxxDescriptionEnhancer.getSandboxSymlinkTreePath(
params.getProjectFilesystem(), sandboxSymlinkTreeTarget);
return new SymlinkTree(
sandboxSymlinkTreeTarget,
params.getProjectFilesystem(),
sandboxSymlinkTreeRoot,
map,
ruleFinder);
}
public static HeaderSymlinkTree requireHeaderSymlinkTree(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleResolver ruleResolver,
CxxPlatform cxxPlatform,
ImmutableMap<Path, SourcePath> headers,
HeaderVisibility headerVisibility,
boolean shouldCreateHeadersSymlinks) {
BuildTarget untypedTarget = CxxLibraryDescription.getUntypedBuildTarget(buildTarget);
BuildTarget headerSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
untypedTarget, headerVisibility, cxxPlatform.getFlavor());
// Check the cache...
return (HeaderSymlinkTree)
ruleResolver.computeIfAbsent(
headerSymlinkTreeTarget,
() ->
createHeaderSymlinkTree(
untypedTarget,
projectFilesystem,
ruleResolver,
cxxPlatform,
headers,
headerVisibility,
shouldCreateHeadersSymlinks));
}
private static SymlinkTree requireSandboxSymlinkTree(
BuildTarget buildTarget, BuildRuleResolver ruleResolver, CxxPlatform cxxPlatform)
throws NoSuchBuildTargetException {
BuildTarget untypedTarget = CxxLibraryDescription.getUntypedBuildTarget(buildTarget);
BuildTarget headerSymlinkTreeTarget =
CxxDescriptionEnhancer.createSandboxSymlinkTreeTarget(
untypedTarget, cxxPlatform.getFlavor());
BuildRule rule = ruleResolver.requireRule(headerSymlinkTreeTarget);
Preconditions.checkState(
rule instanceof SymlinkTree, rule.getBuildTarget() + " " + rule.getClass().toString());
return (SymlinkTree) rule;
}
/**
* @return the {@link BuildTarget} to use for the {@link BuildRule} generating the symlink tree of
* headers.
*/
@VisibleForTesting
public static BuildTarget createHeaderSymlinkTreeTarget(
BuildTarget target, HeaderVisibility headerVisibility, Flavor... flavors) {
return BuildTarget.builder(target)
.addFlavors(getHeaderSymlinkTreeFlavor(headerVisibility))
.addFlavors(flavors)
.build();
}
@VisibleForTesting
public static BuildTarget createSandboxSymlinkTreeTarget(BuildTarget target, Flavor platform) {
return BuildTarget.builder(target).addFlavors(platform).addFlavors(SANDBOX_TREE_FLAVOR).build();
}
/** @return the absolute {@link Path} to use for the symlink tree of headers. */
public static Path getHeaderSymlinkTreePath(
ProjectFilesystem filesystem,
BuildTarget target,
HeaderVisibility headerVisibility,
Flavor... flavors) {
return BuildTargets.getGenPath(
filesystem, createHeaderSymlinkTreeTarget(target, headerVisibility, flavors), "%s");
}
public static Path getSandboxSymlinkTreePath(ProjectFilesystem filesystem, BuildTarget target) {
return BuildTargets.getGenPath(filesystem, target, "%s");
}
public static Flavor getHeaderSymlinkTreeFlavor(HeaderVisibility headerVisibility) {
switch (headerVisibility) {
case PUBLIC:
return EXPORTED_HEADER_SYMLINK_TREE_FLAVOR;
case PRIVATE:
return HEADER_SYMLINK_TREE_FLAVOR;
default:
throw new RuntimeException("Unexpected value of enum ExportMode");
}
}
static ImmutableMap<String, SourcePath> parseOnlyHeaders(
BuildTarget buildTarget,
SourcePathRuleFinder ruleFinder,
SourcePathResolver sourcePathResolver,
String parameterName,
SourceList exportedHeaders) {
return exportedHeaders.toNameMap(
buildTarget,
sourcePathResolver,
parameterName,
path -> !CxxGenruleDescription.wrapsCxxGenrule(ruleFinder, path),
path -> path);
}
static ImmutableMap<String, SourcePath> parseOnlyPlatformHeaders(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver sourcePathResolver,
CxxPlatform cxxPlatform,
String headersParameterName,
SourceList headers,
String platformHeadersParameterName,
PatternMatchedCollection<SourceList> platformHeaders)
throws NoSuchBuildTargetException {
ImmutableMap.Builder<String, SourcePath> parsed = ImmutableMap.builder();
java.util.function.Function<SourcePath, SourcePath> fixup =
path -> {
try {
return CxxGenruleDescription.fixupSourcePath(resolver, ruleFinder, cxxPlatform, path);
} catch (NoSuchBuildTargetException e) {
throw new RuntimeException(e);
}
};
// Include all normal exported headers that are generated by `cxx_genrule`.
parsed.putAll(
headers.toNameMap(
buildTarget,
sourcePathResolver,
headersParameterName,
path -> CxxGenruleDescription.wrapsCxxGenrule(ruleFinder, path),
fixup));
// Include all platform specific headers.
for (SourceList sourceList :
platformHeaders.getMatchingValues(cxxPlatform.getFlavor().toString())) {
parsed.putAll(
sourceList.toNameMap(
buildTarget, sourcePathResolver, platformHeadersParameterName, path -> true, fixup));
}
return parsed.build();
}
/**
* @return a map of header locations to input {@link SourcePath} objects formed by parsing the
* input {@link SourcePath} objects for the "headers" parameter.
*/
public static ImmutableMap<Path, SourcePath> parseHeaders(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver sourcePathResolver,
Optional<CxxPlatform> cxxPlatform,
CxxConstructorArg args)
throws NoSuchBuildTargetException {
ImmutableMap.Builder<String, SourcePath> headers = ImmutableMap.builder();
// Add platform-agnostic headers.
headers.putAll(
parseOnlyHeaders(
buildTarget, ruleFinder, sourcePathResolver, "headers", args.getHeaders()));
// Add platform-specific headers.
if (cxxPlatform.isPresent()) {
headers.putAll(
parseOnlyPlatformHeaders(
buildTarget,
resolver,
ruleFinder,
sourcePathResolver,
cxxPlatform.get(),
"headers",
args.getHeaders(),
"platform_headers",
args.getPlatformHeaders()));
}
return CxxPreprocessables.resolveHeaderMap(
args.getHeaderNamespace().map(Paths::get).orElse(buildTarget.getBasePath()),
headers.build());
}
/**
* @return a map of header locations to input {@link SourcePath} objects formed by parsing the
* input {@link SourcePath} objects for the "exportedHeaders" parameter.
*/
public static ImmutableMap<Path, SourcePath> parseExportedHeaders(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver sourcePathResolver,
Optional<CxxPlatform> cxxPlatform,
CxxLibraryDescription.CommonArg args)
throws NoSuchBuildTargetException {
ImmutableMap.Builder<String, SourcePath> headers = ImmutableMap.builder();
// Include platform-agnostic headers.
headers.putAll(
parseOnlyHeaders(
buildTarget,
ruleFinder,
sourcePathResolver,
"exported_headers",
args.getExportedHeaders()));
// If a platform is specific, include platform-specific headers.
if (cxxPlatform.isPresent()) {
headers.putAll(
parseOnlyPlatformHeaders(
buildTarget,
resolver,
ruleFinder,
sourcePathResolver,
cxxPlatform.get(),
"exported_headers",
args.getExportedHeaders(),
"exported_platform_headers",
args.getExportedPlatformHeaders()));
}
return CxxPreprocessables.resolveHeaderMap(
args.getHeaderNamespace().map(Paths::get).orElse(buildTarget.getBasePath()),
headers.build());
}
/**
* @return a map of header locations to input {@link SourcePath} objects formed by parsing the
* input {@link SourcePath} objects for the "exportedHeaders" parameter.
*/
public static ImmutableMap<Path, SourcePath> parseExportedPlatformHeaders(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver sourcePathResolver,
CxxPlatform cxxPlatform,
CxxLibraryDescription.CommonArg args)
throws NoSuchBuildTargetException {
return CxxPreprocessables.resolveHeaderMap(
args.getHeaderNamespace().map(Paths::get).orElse(buildTarget.getBasePath()),
parseOnlyPlatformHeaders(
buildTarget,
resolver,
ruleFinder,
sourcePathResolver,
cxxPlatform,
"exported_headers",
args.getExportedHeaders(),
"exported_platform_headers",
args.getExportedPlatformHeaders()));
}
/**
* @return a list {@link CxxSource} objects formed by parsing the input {@link SourcePath} objects
* for the "srcs" parameter.
*/
public static ImmutableMap<String, CxxSource> parseCxxSources(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver pathResolver,
CxxPlatform cxxPlatform,
CxxConstructorArg args) {
return parseCxxSources(
buildTarget,
resolver,
ruleFinder,
pathResolver,
cxxPlatform,
args.getSrcs(),
args.getPlatformSrcs());
}
public static ImmutableMap<String, CxxSource> parseCxxSources(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver pathResolver,
CxxPlatform cxxPlatform,
ImmutableSortedSet<SourceWithFlags> srcs,
PatternMatchedCollection<ImmutableSortedSet<SourceWithFlags>> platformSrcs) {
ImmutableMap.Builder<String, SourceWithFlags> sources = ImmutableMap.builder();
putAllSources(buildTarget, resolver, ruleFinder, pathResolver, cxxPlatform, srcs, sources);
for (ImmutableSortedSet<SourceWithFlags> sourcesWithFlags :
platformSrcs.getMatchingValues(cxxPlatform.getFlavor().toString())) {
putAllSources(
buildTarget, resolver, ruleFinder, pathResolver, cxxPlatform, sourcesWithFlags, sources);
}
return resolveCxxSources(sources.build());
}
private static void putAllSources(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver pathResolver,
CxxPlatform cxxPlatform,
ImmutableSortedSet<SourceWithFlags> sourcesWithFlags,
ImmutableMap.Builder<String, SourceWithFlags> sources) {
sources.putAll(
pathResolver.getSourcePathNames(
buildTarget,
"srcs",
sourcesWithFlags
.stream()
.map(
s -> {
try {
return s.withSourcePath(
CxxGenruleDescription.fixupSourcePath(
resolver,
ruleFinder,
cxxPlatform,
Preconditions.checkNotNull(s.getSourcePath())));
} catch (NoSuchBuildTargetException e) {
throw new RuntimeException(e);
}
})
.collect(MoreCollectors.toImmutableList()),
x -> true,
SourceWithFlags::getSourcePath));
}
public static ImmutableList<CxxPreprocessorInput> collectCxxPreprocessorInput(
BuildTarget target,
CxxPlatform cxxPlatform,
Iterable<BuildRule> deps,
ImmutableMultimap<CxxSource.Type, String> preprocessorFlags,
ImmutableList<HeaderSymlinkTree> headerSymlinkTrees,
ImmutableSet<FrameworkPath> frameworks,
Iterable<CxxPreprocessorInput> cxxPreprocessorInputFromDeps,
ImmutableList<String> includeDirs,
Optional<SymlinkTree> symlinkTree)
throws NoSuchBuildTargetException {
// Add the private includes of any rules which this rule depends on, and which list this rule as
// a test.
BuildTarget targetWithoutFlavor = BuildTarget.of(target.getUnflavoredBuildTarget());
ImmutableList.Builder<CxxPreprocessorInput> cxxPreprocessorInputFromTestedRulesBuilder =
ImmutableList.builder();
for (BuildRule rule : deps) {
if (rule instanceof NativeTestable) {
NativeTestable testable = (NativeTestable) rule;
if (testable.isTestedBy(targetWithoutFlavor)) {
LOG.debug(
"Adding private includes of tested rule %s to testing rule %s",
rule.getBuildTarget(), target);
cxxPreprocessorInputFromTestedRulesBuilder.add(
testable.getPrivateCxxPreprocessorInput(cxxPlatform));
// Add any dependent headers
cxxPreprocessorInputFromTestedRulesBuilder.addAll(
CxxPreprocessables.getTransitiveCxxPreprocessorInput(
cxxPlatform, ImmutableList.of(rule)));
}
}
}
ImmutableList<CxxPreprocessorInput> cxxPreprocessorInputFromTestedRules =
cxxPreprocessorInputFromTestedRulesBuilder.build();
LOG.verbose(
"Rules tested by target %s added private includes %s",
target, cxxPreprocessorInputFromTestedRules);
ImmutableList.Builder<CxxHeaders> allIncludes = ImmutableList.builder();
for (HeaderSymlinkTree headerSymlinkTree : headerSymlinkTrees) {
allIncludes.add(
CxxSymlinkTreeHeaders.from(headerSymlinkTree, CxxPreprocessables.IncludeType.LOCAL));
}
CxxPreprocessorInput.Builder builder = CxxPreprocessorInput.builder();
builder.putAllPreprocessorFlags(preprocessorFlags);
// headers from #sandbox are put before #private-headers and #headers on purpose
// this is the only way to control windows behavior
if (symlinkTree.isPresent()) {
for (String includeDir : includeDirs) {
builder.addIncludes(
CxxSandboxInclude.from(
symlinkTree.get(), includeDir, CxxPreprocessables.IncludeType.LOCAL));
}
}
builder.addAllIncludes(allIncludes.build()).addAllFrameworks(frameworks);
CxxPreprocessorInput localPreprocessorInput = builder.build();
return ImmutableList.<CxxPreprocessorInput>builder()
.add(localPreprocessorInput)
.addAll(cxxPreprocessorInputFromDeps)
.addAll(cxxPreprocessorInputFromTestedRules)
.build();
}
public static BuildTarget createStaticLibraryBuildTarget(
BuildTarget target, Flavor platform, CxxSourceRuleFactory.PicType pic) {
return BuildTarget.builder(target)
.addFlavors(platform)
.addFlavors(pic == CxxSourceRuleFactory.PicType.PDC ? STATIC_FLAVOR : STATIC_PIC_FLAVOR)
.build();
}
public static BuildTarget createSharedLibraryBuildTarget(
BuildTarget target, Flavor platform, Linker.LinkType linkType) {
Flavor linkFlavor;
switch (linkType) {
case SHARED:
linkFlavor = SHARED_FLAVOR;
break;
case MACH_O_BUNDLE:
linkFlavor = MACH_O_BUNDLE_FLAVOR;
break;
case EXECUTABLE:
default:
throw new IllegalStateException(
"Only SHARED and MACH_O_BUNDLE types expected, got: " + linkType);
}
return BuildTarget.builder(target).addFlavors(platform).addFlavors(linkFlavor).build();
}
public static Path getStaticLibraryPath(
ProjectFilesystem filesystem,
BuildTarget target,
Flavor platform,
CxxSourceRuleFactory.PicType pic,
String extension) {
return getStaticLibraryPath(filesystem, target, platform, pic, extension, "");
}
public static Path getStaticLibraryPath(
ProjectFilesystem filesystem,
BuildTarget target,
Flavor platform,
CxxSourceRuleFactory.PicType pic,
String extension,
String suffix) {
String name = String.format("lib%s%s.%s", target.getShortName(), suffix, extension);
return BuildTargets.getGenPath(
filesystem, createStaticLibraryBuildTarget(target, platform, pic), "%s")
.resolve(name);
}
public static String getSharedLibrarySoname(
Optional<String> declaredSoname, BuildTarget target, CxxPlatform platform) {
if (!declaredSoname.isPresent()) {
return getDefaultSharedLibrarySoname(target, platform);
}
return getNonDefaultSharedLibrarySoname(
declaredSoname.get(),
platform.getSharedLibraryExtension(),
platform.getSharedLibraryVersionedExtensionFormat());
}
@VisibleForTesting
static String getNonDefaultSharedLibrarySoname(
String declared,
String sharedLibraryExtension,
String sharedLibraryVersionedExtensionFormat) {
Matcher match = SONAME_EXT_MACRO_PATTERN.matcher(declared);
if (!match.find()) {
return declared;
}
String version = match.group(1);
if (version == null) {
return match.replaceFirst(sharedLibraryExtension);
}
return match.replaceFirst(String.format(sharedLibraryVersionedExtensionFormat, version));
}
public static String getDefaultSharedLibrarySoname(BuildTarget target, CxxPlatform platform) {
String libName =
Joiner.on('_')
.join(
ImmutableList.builder()
.addAll(
StreamSupport.stream(target.getBasePath().spliterator(), false)
.map(Object::toString)
.filter(x -> !x.isEmpty())
.iterator())
.add(target.getShortName())
.build());
String extension = platform.getSharedLibraryExtension();
return String.format("lib%s.%s", libName, extension);
}
public static Path getSharedLibraryPath(
ProjectFilesystem filesystem, BuildTarget sharedLibraryTarget, String soname) {
return BuildTargets.getGenPath(filesystem, sharedLibraryTarget, "%s/" + soname);
}
private static Path getBinaryOutputPath(
BuildTarget target, ProjectFilesystem filesystem, Optional<String> extension) {
String format = extension.map(ext -> "%s." + ext).orElse("%s");
return BuildTargets.getGenPath(filesystem, target, format);
}
@VisibleForTesting
public static BuildTarget createCxxLinkTarget(
BuildTarget target, Optional<LinkerMapMode> flavoredLinkerMapMode) {
if (flavoredLinkerMapMode.isPresent()) {
target = target.withAppendedFlavors(flavoredLinkerMapMode.get().getFlavor());
}
return target.withAppendedFlavors(CXX_LINK_BINARY_FLAVOR);
}
/**
* @return a function that transforms the {@link FrameworkPath} to search paths with any embedded
* macros expanded.
*/
public static RuleKeyAppendableFunction<FrameworkPath, Path> frameworkPathToSearchPath(
final CxxPlatform cxxPlatform, final SourcePathResolver resolver) {
return new RuleKeyAppendableFunction<FrameworkPath, Path>() {
private RuleKeyAppendableFunction<String, String> translateMacrosFn =
CxxFlags.getTranslateMacrosFn(cxxPlatform);
@Override
public void appendToRuleKey(RuleKeyObjectSink sink) {
sink.setReflectively("translateMacrosFn", translateMacrosFn);
}
@Override
public Path apply(FrameworkPath input) {
String pathAsString =
FrameworkPath.getUnexpandedSearchPath(
resolver::getAbsolutePath, Functions.identity(), input)
.toString();
return Paths.get(translateMacrosFn.apply(pathAsString));
}
};
}
public static CxxLinkAndCompileRules createBuildRulesForCxxBinaryDescriptionArg(
TargetGraph targetGraph,
BuildRuleParams params,
BuildRuleResolver resolver,
CellPathResolver cellRoots,
CxxBuckConfig cxxBuckConfig,
CxxPlatform cxxPlatform,
CxxBinaryDescription.CommonArg args,
ImmutableSet<BuildTarget> extraDeps,
Optional<StripStyle> stripStyle,
Optional<LinkerMapMode> flavoredLinkerMapMode)
throws NoSuchBuildTargetException {
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
ImmutableMap<String, CxxSource> srcs =
parseCxxSources(
params.getBuildTarget(), resolver, ruleFinder, pathResolver, cxxPlatform, args);
ImmutableMap<Path, SourcePath> headers =
parseHeaders(
params.getBuildTarget(),
resolver,
ruleFinder,
pathResolver,
Optional.of(cxxPlatform),
args);
// Build the binary deps.
ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder();
// Add original declared and extra deps.
args.getCxxDeps().get(resolver, cxxPlatform).forEach(depsBuilder::add);
// Add in deps found via deps query.
args.getDepsQuery()
.ifPresent(
query ->
QueryUtils.resolveDepQuery(
params.getBuildTarget(),
query,
resolver,
cellRoots,
targetGraph,
args.getDeps())
.forEach(depsBuilder::add));
// Add any extra deps passed in.
extraDeps.stream().map(resolver::getRule).forEach(depsBuilder::add);
ImmutableSortedSet<BuildRule> deps = depsBuilder.build();
return createBuildRulesForCxxBinary(
params,
resolver,
cellRoots,
cxxBuckConfig,
cxxPlatform,
srcs,
headers,
deps,
stripStyle,
flavoredLinkerMapMode,
args.getLinkStyle().orElse(Linker.LinkableDepType.STATIC),
args.getThinLto(),
args.getPreprocessorFlags(),
args.getPlatformPreprocessorFlags(),
args.getLangPreprocessorFlags(),
args.getFrameworks(),
args.getLibraries(),
args.getCompilerFlags(),
args.getLangCompilerFlags(),
args.getPlatformCompilerFlags(),
args.getPrefixHeader(),
args.getPrecompiledHeader(),
args.getLinkerFlags(),
args.getPlatformLinkerFlags(),
args.getCxxRuntimeType(),
args.getIncludeDirs(),
Optional.empty());
}
public static CxxLinkAndCompileRules createBuildRulesForCxxBinary(
BuildRuleParams params,
BuildRuleResolver resolver,
CellPathResolver cellRoots,
CxxBuckConfig cxxBuckConfig,
CxxPlatform cxxPlatform,
ImmutableMap<String, CxxSource> srcs,
ImmutableMap<Path, SourcePath> headers,
SortedSet<BuildRule> deps,
Optional<StripStyle> stripStyle,
Optional<LinkerMapMode> flavoredLinkerMapMode,
Linker.LinkableDepType linkStyle,
boolean thinLto,
ImmutableList<String> preprocessorFlags,
PatternMatchedCollection<ImmutableList<String>> platformPreprocessorFlags,
ImmutableMap<CxxSource.Type, ImmutableList<String>> langPreprocessorFlags,
ImmutableSortedSet<FrameworkPath> frameworks,
ImmutableSortedSet<FrameworkPath> libraries,
ImmutableList<String> compilerFlags,
ImmutableMap<CxxSource.Type, ImmutableList<String>> langCompilerFlags,
PatternMatchedCollection<ImmutableList<String>> platformCompilerFlags,
Optional<SourcePath> prefixHeader,
Optional<SourcePath> precompiledHeader,
ImmutableList<StringWithMacros> linkerFlags,
PatternMatchedCollection<ImmutableList<StringWithMacros>> platformLinkerFlags,
Optional<Linker.CxxRuntimeType> cxxRuntimeType,
ImmutableList<String> includeDirs,
Optional<Boolean> xcodePrivateHeadersSymlinks)
throws NoSuchBuildTargetException {
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
SourcePathResolver sourcePathResolver = new SourcePathResolver(ruleFinder);
// TODO(beefon): should be:
// Path linkOutput = getLinkOutputPath(
// createCxxLinkTarget(params.getBuildTarget(), flavoredLinkerMapMode),
// params.getProjectFilesystem());
BuildTarget target = params.getBuildTarget();
if (flavoredLinkerMapMode.isPresent()) {
target = target.withAppendedFlavors(flavoredLinkerMapMode.get().getFlavor());
}
Path linkOutput =
getBinaryOutputPath(
target, params.getProjectFilesystem(), cxxPlatform.getBinaryExtension());
ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();
CommandTool.Builder executableBuilder = new CommandTool.Builder();
// Setup the header symlink tree and combine all the preprocessor input from this rule
// and all dependencies.
boolean shouldCreatePrivateHeadersSymlinks =
xcodePrivateHeadersSymlinks.orElse(cxxBuckConfig.getPrivateHeadersSymlinksEnabled());
HeaderSymlinkTree headerSymlinkTree =
requireHeaderSymlinkTree(
params.getBuildTarget(),
params.getProjectFilesystem(),
resolver,
cxxPlatform,
headers,
HeaderVisibility.PRIVATE,
shouldCreatePrivateHeadersSymlinks);
Optional<SymlinkTree> sandboxTree = Optional.empty();
if (cxxBuckConfig.sandboxSources()) {
sandboxTree = createSandboxTree(params.getBuildTarget(), resolver, cxxPlatform);
}
ImmutableList<CxxPreprocessorInput> cxxPreprocessorInput =
collectCxxPreprocessorInput(
params.getBuildTarget(),
cxxPlatform,
deps,
CxxFlags.getLanguageFlags(
preprocessorFlags, platformPreprocessorFlags, langPreprocessorFlags, cxxPlatform),
ImmutableList.of(headerSymlinkTree),
frameworks,
CxxPreprocessables.getTransitiveCxxPreprocessorInput(
cxxPlatform,
RichStream.from(deps)
.filter(CxxPreprocessorDep.class::isInstance)
.toImmutableList()),
includeDirs,
sandboxTree);
ImmutableList.Builder<String> compilerFlagsWithLto = ImmutableList.builder();
compilerFlagsWithLto.addAll(compilerFlags);
if (thinLto) {
compilerFlagsWithLto.add("-flto=thin");
}
// Generate and add all the build rules to preprocess and compile the source to the
// resolver and get the `SourcePath`s representing the generated object files.
ImmutableMap<CxxPreprocessAndCompile, SourcePath> objects =
CxxSourceRuleFactory.requirePreprocessAndCompileRules(
params.getProjectFilesystem(),
params.getBuildTarget(),
resolver,
sourcePathResolver,
ruleFinder,
cxxBuckConfig,
cxxPlatform,
cxxPreprocessorInput,
CxxFlags.getLanguageFlags(
compilerFlagsWithLto.build(),
platformCompilerFlags,
langCompilerFlags,
cxxPlatform),
prefixHeader,
precompiledHeader,
srcs,
linkStyle == Linker.LinkableDepType.STATIC
? CxxSourceRuleFactory.PicType.PDC
: CxxSourceRuleFactory.PicType.PIC,
sandboxTree);
// Build up the linker flags, which support macro expansion.
argsBuilder.addAll(
toStringWithMacrosArgs(
target,
cellRoots,
resolver,
cxxPlatform,
CxxFlags.getFlagsWithMacrosWithPlatformMacroExpansion(
linkerFlags, platformLinkerFlags, cxxPlatform)));
// Special handling for dynamically linked binaries.
if (linkStyle == Linker.LinkableDepType.SHARED) {
// Create a symlink tree with for all shared libraries needed by this binary.
SymlinkTree sharedLibraries =
requireSharedLibrarySymlinkTree(
params.getBuildTarget(),
params.getProjectFilesystem(),
resolver,
ruleFinder,
cxxPlatform,
deps,
NativeLinkable.class::isInstance);
// Embed a origin-relative library path into the binary so it can find the shared libraries.
// The shared libraries root is absolute. Also need an absolute path to the linkOutput
Path absLinkOut = params.getBuildTarget().getCellPath().resolve(linkOutput);
argsBuilder.addAll(
StringArg.from(
Linkers.iXlinker(
"-rpath",
String.format(
"%s/%s",
cxxPlatform.getLd().resolve(resolver).origin(),
absLinkOut.getParent().relativize(sharedLibraries.getRoot()).toString()))));
// Add all the shared libraries and the symlink tree as inputs to the tool that represents
// this binary, so that users can attach the proper deps.
executableBuilder.addDep(sharedLibraries);
executableBuilder.addInputs(sharedLibraries.getLinks().values());
}
// Add object files into the args.
ImmutableList<SourcePathArg> objectArgs =
SourcePathArg.from(objects.values())
.stream()
.map(
input -> {
Preconditions.checkArgument(input instanceof SourcePathArg);
return (SourcePathArg) input;
})
.collect(MoreCollectors.toImmutableList());
argsBuilder.addAll(FileListableLinkerInputArg.from(objectArgs));
BuildTarget linkRuleTarget =
createCxxLinkTarget(params.getBuildTarget(), flavoredLinkerMapMode);
CxxLink cxxLink =
createCxxLinkRule(
params,
resolver,
cxxBuckConfig,
cxxPlatform,
RichStream.from(deps).filter(NativeLinkable.class).toImmutableList(),
linkStyle,
thinLto,
frameworks,
libraries,
cxxRuntimeType,
sourcePathResolver,
ruleFinder,
linkOutput,
argsBuilder,
linkRuleTarget);
BuildRule binaryRuleForExecutable;
Optional<CxxStrip> cxxStrip = Optional.empty();
if (stripStyle.isPresent()) {
BuildRuleParams cxxParams = params;
if (flavoredLinkerMapMode.isPresent()) {
cxxParams = params.withAppendedFlavor(flavoredLinkerMapMode.get().getFlavor());
}
CxxStrip stripRule =
createCxxStripRule(cxxParams, resolver, stripStyle.get(), cxxLink, cxxPlatform);
cxxStrip = Optional.of(stripRule);
binaryRuleForExecutable = stripRule;
} else {
binaryRuleForExecutable = cxxLink;
}
// Add the output of the link as the lone argument needed to invoke this binary as a tool.
executableBuilder.addArg(SourcePathArg.of(binaryRuleForExecutable.getSourcePathToOutput()));
return new CxxLinkAndCompileRules(
cxxLink,
cxxStrip,
ImmutableSortedSet.copyOf(objects.keySet()),
executableBuilder.build(),
deps);
}
private static CxxLink createCxxLinkRule(
BuildRuleParams params,
BuildRuleResolver resolver,
CxxBuckConfig cxxBuckConfig,
CxxPlatform cxxPlatform,
Iterable<? extends NativeLinkable> deps,
Linker.LinkableDepType linkStyle,
boolean thinLto,
ImmutableSortedSet<FrameworkPath> frameworks,
ImmutableSortedSet<FrameworkPath> libraries,
Optional<Linker.CxxRuntimeType> cxxRuntimeType,
SourcePathResolver sourcePathResolver,
SourcePathRuleFinder ruleFinder,
Path linkOutput,
ImmutableList.Builder<Arg> argsBuilder,
BuildTarget linkRuleTarget)
throws NoSuchBuildTargetException {
return (CxxLink)
resolver.computeIfAbsentThrowing(
linkRuleTarget,
() ->
// Generate the final link rule. We use the top-level target as the link rule's
// target, so that it corresponds to the actual binary we build.
CxxLinkableEnhancer.createCxxLinkableBuildRule(
cxxBuckConfig,
cxxPlatform,
params,
resolver,
sourcePathResolver,
ruleFinder,
linkRuleTarget,
Linker.LinkType.EXECUTABLE,
Optional.empty(),
linkOutput,
linkStyle,
thinLto,
deps,
cxxRuntimeType,
Optional.empty(),
ImmutableSet.of(),
NativeLinkableInput.builder()
.setArgs(argsBuilder.build())
.setFrameworks(frameworks)
.setLibraries(libraries)
.build(),
Optional.empty()));
}
public static CxxStrip createCxxStripRule(
BuildRuleParams params,
BuildRuleResolver resolver,
StripStyle stripStyle,
BuildRule unstrippedBinaryRule,
CxxPlatform cxxPlatform) {
BuildRuleParams stripRuleParams =
params
.withBuildTarget(
params
.getBuildTarget()
.withAppendedFlavors(CxxStrip.RULE_FLAVOR, stripStyle.getFlavor()))
.copyReplacingDeclaredAndExtraDeps(
ImmutableSortedSet.of(unstrippedBinaryRule), ImmutableSortedSet.of());
return (CxxStrip)
resolver.computeIfAbsent(
stripRuleParams.getBuildTarget(),
() ->
new CxxStrip(
stripRuleParams,
stripStyle,
Preconditions.checkNotNull(unstrippedBinaryRule.getSourcePathToOutput()),
cxxPlatform.getStrip(),
CxxDescriptionEnhancer.getBinaryOutputPath(
stripRuleParams.getBuildTarget(),
params.getProjectFilesystem(),
cxxPlatform.getBinaryExtension())));
}
public static BuildRule createUberCompilationDatabase(
BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleResolver ruleResolver)
throws NoSuchBuildTargetException {
Optional<CxxCompilationDatabaseDependencies> compilationDatabases =
ruleResolver.requireMetadata(
buildTarget
.withoutFlavors(CxxCompilationDatabase.UBER_COMPILATION_DATABASE)
.withAppendedFlavors(CxxCompilationDatabase.COMPILATION_DATABASE),
CxxCompilationDatabaseDependencies.class);
Preconditions.checkState(compilationDatabases.isPresent());
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver);
SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
return new JsonConcatenate(
new BuildRuleParams(
buildTarget,
() ->
ImmutableSortedSet.copyOf(
ruleFinder.filterBuildRuleInputs(compilationDatabases.get().getSourcePaths())),
() -> ImmutableSortedSet.of(),
ImmutableSortedSet.of(),
projectFilesystem),
pathResolver.getAllAbsolutePaths(compilationDatabases.get().getSourcePaths()),
"compilation-database-concatenate",
"Concatenate compilation databases",
"uber-compilation-database",
"compile_commands.json");
}
public static Optional<CxxCompilationDatabaseDependencies> createCompilationDatabaseDependencies(
BuildTarget buildTarget,
FlavorDomain<CxxPlatform> platforms,
BuildRuleResolver resolver,
CxxConstructorArg args)
throws NoSuchBuildTargetException {
Preconditions.checkState(
buildTarget.getFlavors().contains(CxxCompilationDatabase.COMPILATION_DATABASE));
Optional<Flavor> cxxPlatformFlavor = platforms.getFlavor(buildTarget);
Preconditions.checkState(
cxxPlatformFlavor.isPresent(),
"Could not find cxx platform in:\n%s",
Joiner.on(", ").join(buildTarget.getFlavors()));
ImmutableSet.Builder<SourcePath> sourcePaths = ImmutableSet.builder();
for (BuildTarget dep : args.getDeps()) {
Optional<CxxCompilationDatabaseDependencies> compilationDatabases =
resolver.requireMetadata(
BuildTarget.builder(dep)
.addFlavors(CxxCompilationDatabase.COMPILATION_DATABASE)
.addFlavors(cxxPlatformFlavor.get())
.build(),
CxxCompilationDatabaseDependencies.class);
if (compilationDatabases.isPresent()) {
sourcePaths.addAll(compilationDatabases.get().getSourcePaths());
}
}
// Not all parts of Buck use require yet, so require the rule here so it's available in the
// resolver for the parts that don't.
BuildRule buildRule = resolver.requireRule(buildTarget);
sourcePaths.add(buildRule.getSourcePathToOutput());
return Optional.of(CxxCompilationDatabaseDependencies.of(sourcePaths.build()));
}
public static Optional<SymlinkTree> createSandboxTree(
BuildTarget buildTarget, BuildRuleResolver ruleResolver, CxxPlatform cxxPlatform)
throws NoSuchBuildTargetException {
return Optional.of(requireSandboxSymlinkTree(buildTarget, ruleResolver, cxxPlatform));
}
/**
* @return the {@link BuildTarget} to use for the {@link BuildRule} generating the symlink tree of
* shared libraries.
*/
public static BuildTarget createSharedLibrarySymlinkTreeTarget(
BuildTarget target, Flavor platform) {
return BuildTarget.builder(target)
.addFlavors(SHARED_LIBRARY_SYMLINK_TREE_FLAVOR)
.addFlavors(platform)
.build();
}
/** @return the {@link Path} to use for the symlink tree of headers. */
public static Path getSharedLibrarySymlinkTreePath(
ProjectFilesystem filesystem, BuildTarget target, Flavor platform) {
return BuildTargets.getGenPath(
filesystem, createSharedLibrarySymlinkTreeTarget(target, platform), "%s");
}
/**
* Build a {@link HeaderSymlinkTree} of all the shared libraries found via the top-level rule's
* transitive dependencies.
*/
public static SymlinkTree createSharedLibrarySymlinkTree(
SourcePathRuleFinder ruleFinder,
BuildTarget baseBuildTarget,
ProjectFilesystem filesystem,
CxxPlatform cxxPlatform,
Iterable<? extends BuildRule> deps,
Predicate<Object> traverse,
Predicate<Object> skip)
throws NoSuchBuildTargetException {
BuildTarget symlinkTreeTarget =
createSharedLibrarySymlinkTreeTarget(baseBuildTarget, cxxPlatform.getFlavor());
Path symlinkTreeRoot =
getSharedLibrarySymlinkTreePath(filesystem, baseBuildTarget, cxxPlatform.getFlavor());
ImmutableSortedMap<String, SourcePath> libraries =
NativeLinkables.getTransitiveSharedLibraries(cxxPlatform, deps, traverse, skip);
ImmutableMap.Builder<Path, SourcePath> links = ImmutableMap.builder();
for (Map.Entry<String, SourcePath> ent : libraries.entrySet()) {
links.put(Paths.get(ent.getKey()), ent.getValue());
}
return new SymlinkTree(
symlinkTreeTarget, filesystem, symlinkTreeRoot, links.build(), ruleFinder);
}
public static SymlinkTree createSharedLibrarySymlinkTree(
SourcePathRuleFinder ruleFinder,
BuildTarget baseBuildTarget,
ProjectFilesystem filesystem,
CxxPlatform cxxPlatform,
Iterable<? extends BuildRule> deps,
Predicate<Object> traverse)
throws NoSuchBuildTargetException {
return createSharedLibrarySymlinkTree(
ruleFinder, baseBuildTarget, filesystem, cxxPlatform, deps, traverse, x -> false);
}
public static SymlinkTree requireSharedLibrarySymlinkTree(
BuildTarget buildTarget,
ProjectFilesystem filesystem,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
CxxPlatform cxxPlatform,
Iterable<? extends BuildRule> deps,
Predicate<Object> traverse)
throws NoSuchBuildTargetException {
BuildTarget target = createSharedLibrarySymlinkTreeTarget(buildTarget, cxxPlatform.getFlavor());
SymlinkTree tree = resolver.getRuleOptionalWithType(target, SymlinkTree.class).orElse(null);
if (tree == null) {
tree =
resolver.addToIndex(
createSharedLibrarySymlinkTree(
ruleFinder, buildTarget, filesystem, cxxPlatform, deps, traverse));
}
return tree;
}
public static Flavor flavorForLinkableDepType(Linker.LinkableDepType linkableDepType) {
switch (linkableDepType) {
case STATIC:
return STATIC_FLAVOR;
case STATIC_PIC:
return STATIC_PIC_FLAVOR;
case SHARED:
return SHARED_FLAVOR;
}
throw new RuntimeException(String.format("Unsupported LinkableDepType: '%s'", linkableDepType));
}
public static SymlinkTree createSandboxTreeBuildRule(
BuildRuleResolver resolver,
CxxConstructorArg args,
CxxPlatform platform,
BuildRuleParams params)
throws NoSuchBuildTargetException {
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
SourcePathResolver sourcePathResolver = new SourcePathResolver(ruleFinder);
ImmutableCollection<SourcePath> privateHeaders =
parseHeaders(
params.getBuildTarget(),
resolver,
ruleFinder,
sourcePathResolver,
Optional.of(platform),
args)
.values();
ImmutableCollection<CxxSource> sources =
parseCxxSources(
params.getBuildTarget(), resolver, ruleFinder, sourcePathResolver, platform, args)
.values();
HashMap<Path, SourcePath> links = new HashMap<>();
for (SourcePath headerPath : privateHeaders) {
links.put(
Paths.get(sourcePathResolver.getSourcePathName(params.getBuildTarget(), headerPath)),
headerPath);
}
if (args instanceof CxxLibraryDescription.CommonArg) {
ImmutableCollection<SourcePath> publicHeaders =
CxxDescriptionEnhancer.parseExportedHeaders(
params.getBuildTarget(),
resolver,
ruleFinder,
sourcePathResolver,
Optional.of(platform),
(CxxLibraryDescription.CommonArg) args)
.values();
for (SourcePath headerPath : publicHeaders) {
links.put(
Paths.get(sourcePathResolver.getSourcePathName(params.getBuildTarget(), headerPath)),
headerPath);
}
}
for (CxxSource source : sources) {
SourcePath sourcePath = source.getPath();
links.put(
Paths.get(sourcePathResolver.getSourcePathName(params.getBuildTarget(), sourcePath)),
sourcePath);
}
return createSandboxSymlinkTree(params, platform, ImmutableMap.copyOf(links), ruleFinder);
}
/** Resolve the map of names to SourcePaths to a map of names to CxxSource objects. */
private static ImmutableMap<String, CxxSource> resolveCxxSources(
ImmutableMap<String, SourceWithFlags> sources) {
ImmutableMap.Builder<String, CxxSource> cxxSources = ImmutableMap.builder();
// For each entry in the input C/C++ source, build a CxxSource object to wrap
// it's name, input path, and output object file path.
for (ImmutableMap.Entry<String, SourceWithFlags> ent : sources.entrySet()) {
String extension = Files.getFileExtension(ent.getKey());
Optional<CxxSource.Type> type = CxxSource.Type.fromExtension(extension);
if (!type.isPresent()) {
throw new HumanReadableException("invalid extension \"%s\": %s", extension, ent.getKey());
}
cxxSources.put(
ent.getKey(),
CxxSource.of(type.get(), ent.getValue().getSourcePath(), ent.getValue().getFlags()));
}
return cxxSources.build();
}
public static ImmutableList<StringWithMacrosArg> toStringWithMacrosArgs(
BuildTarget target,
CellPathResolver cellPathResolver,
BuildRuleResolver resolver,
CxxPlatform cxxPlatform,
Iterable<StringWithMacros> flags) {
ImmutableList.Builder<StringWithMacrosArg> args = ImmutableList.builder();
for (StringWithMacros flag : flags) {
args.add(
StringWithMacrosArg.of(
flag,
ImmutableList.of(new CxxLocationMacroExpander(cxxPlatform)),
target,
cellPathResolver,
resolver));
}
return args.build();
}
public static String normalizeModuleName(String moduleName) {
return moduleName.replaceAll("[^A-Za-z0-9]", "_");
}
}
| src/com/facebook/buck/cxx/CxxDescriptionEnhancer.java | /*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cxx;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.json.JsonConcatenate;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.FlavorDomain;
import com.facebook.buck.model.InternalFlavor;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.CommandTool;
import com.facebook.buck.rules.RuleKeyObjectSink;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.SourceWithFlags;
import com.facebook.buck.rules.SymlinkTree;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.FileListableLinkerInputArg;
import com.facebook.buck.rules.args.RuleKeyAppendableFunction;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.rules.args.StringWithMacrosArg;
import com.facebook.buck.rules.coercer.FrameworkPath;
import com.facebook.buck.rules.coercer.PatternMatchedCollection;
import com.facebook.buck.rules.coercer.SourceList;
import com.facebook.buck.rules.macros.LocationMacroExpander;
import com.facebook.buck.rules.macros.MacroHandler;
import com.facebook.buck.rules.macros.StringWithMacros;
import com.facebook.buck.rules.query.QueryUtils;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.MoreCollectors;
import com.facebook.buck.util.RichStream;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.io.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.SortedSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.StreamSupport;
public class CxxDescriptionEnhancer {
private static final Logger LOG = Logger.get(CxxDescriptionEnhancer.class);
public static final Flavor SANDBOX_TREE_FLAVOR = InternalFlavor.of("sandbox");
public static final Flavor HEADER_SYMLINK_TREE_FLAVOR = InternalFlavor.of("private-headers");
public static final Flavor EXPORTED_HEADER_SYMLINK_TREE_FLAVOR = InternalFlavor.of("headers");
public static final Flavor STATIC_FLAVOR = InternalFlavor.of("static");
public static final Flavor STATIC_PIC_FLAVOR = InternalFlavor.of("static-pic");
public static final Flavor SHARED_FLAVOR = InternalFlavor.of("shared");
public static final Flavor MACH_O_BUNDLE_FLAVOR = InternalFlavor.of("mach-o-bundle");
public static final Flavor SHARED_LIBRARY_SYMLINK_TREE_FLAVOR =
InternalFlavor.of("shared-library-symlink-tree");
public static final Flavor CXX_LINK_BINARY_FLAVOR = InternalFlavor.of("binary");
protected static final MacroHandler MACRO_HANDLER =
new MacroHandler(ImmutableMap.of("location", new LocationMacroExpander()));
private static final Pattern SONAME_EXT_MACRO_PATTERN =
Pattern.compile("\\$\\(ext(?: ([.0-9]+))?\\)");
private CxxDescriptionEnhancer() {}
public static CxxPreprocessables.HeaderMode getHeaderModeForPlatform(
BuildRuleResolver resolver, CxxPlatform cxxPlatform, boolean shouldCreateHeadersSymlinks) {
boolean useHeaderMap =
(cxxPlatform.getCpp().resolve(resolver).supportsHeaderMaps()
&& cxxPlatform.getCxxpp().resolve(resolver).supportsHeaderMaps());
return !useHeaderMap
? CxxPreprocessables.HeaderMode.SYMLINK_TREE_ONLY
: (shouldCreateHeadersSymlinks
? CxxPreprocessables.HeaderMode.SYMLINK_TREE_WITH_HEADER_MAP
: CxxPreprocessables.HeaderMode.HEADER_MAP_ONLY);
}
public static HeaderSymlinkTree createHeaderSymlinkTree(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleResolver resolver,
CxxPreprocessables.HeaderMode mode,
ImmutableMap<Path, SourcePath> headers,
HeaderVisibility headerVisibility,
Flavor... flavors) {
BuildTarget headerSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
buildTarget, headerVisibility, flavors);
Path headerSymlinkTreeRoot =
CxxDescriptionEnhancer.getHeaderSymlinkTreePath(
projectFilesystem, buildTarget, headerVisibility, flavors);
return CxxPreprocessables.createHeaderSymlinkTreeBuildRule(
headerSymlinkTreeTarget,
projectFilesystem,
headerSymlinkTreeRoot,
headers,
mode,
new SourcePathRuleFinder(resolver));
}
public static HeaderSymlinkTree createHeaderSymlinkTree(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleResolver resolver,
CxxPlatform cxxPlatform,
ImmutableMap<Path, SourcePath> headers,
HeaderVisibility headerVisibility,
boolean shouldCreateHeadersSymlinks) {
return createHeaderSymlinkTree(
buildTarget,
projectFilesystem,
resolver,
getHeaderModeForPlatform(resolver, cxxPlatform, shouldCreateHeadersSymlinks),
headers,
headerVisibility,
cxxPlatform.getFlavor());
}
public static SymlinkTree createSandboxSymlinkTree(
BuildRuleParams params,
CxxPlatform cxxPlatform,
ImmutableMap<Path, SourcePath> map,
SourcePathRuleFinder ruleFinder) {
BuildTarget sandboxSymlinkTreeTarget =
CxxDescriptionEnhancer.createSandboxSymlinkTreeTarget(
params.getBuildTarget(), cxxPlatform.getFlavor());
Path sandboxSymlinkTreeRoot =
CxxDescriptionEnhancer.getSandboxSymlinkTreePath(
params.getProjectFilesystem(), sandboxSymlinkTreeTarget);
return new SymlinkTree(
sandboxSymlinkTreeTarget,
params.getProjectFilesystem(),
sandboxSymlinkTreeRoot,
map,
ruleFinder);
}
public static HeaderSymlinkTree requireHeaderSymlinkTree(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleResolver ruleResolver,
CxxPlatform cxxPlatform,
ImmutableMap<Path, SourcePath> headers,
HeaderVisibility headerVisibility,
boolean shouldCreateHeadersSymlinks) {
BuildTarget untypedTarget = CxxLibraryDescription.getUntypedBuildTarget(buildTarget);
BuildTarget headerSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
untypedTarget, headerVisibility, cxxPlatform.getFlavor());
// Check the cache...
Optional<BuildRule> rule = ruleResolver.getRuleOptional(headerSymlinkTreeTarget);
if (rule.isPresent()) {
Preconditions.checkState(rule.get() instanceof HeaderSymlinkTree);
return (HeaderSymlinkTree) rule.get();
}
HeaderSymlinkTree symlinkTree =
createHeaderSymlinkTree(
untypedTarget,
projectFilesystem,
ruleResolver,
cxxPlatform,
headers,
headerVisibility,
shouldCreateHeadersSymlinks);
ruleResolver.addToIndex(symlinkTree);
return symlinkTree;
}
private static SymlinkTree requireSandboxSymlinkTree(
BuildTarget buildTarget, BuildRuleResolver ruleResolver, CxxPlatform cxxPlatform)
throws NoSuchBuildTargetException {
BuildTarget untypedTarget = CxxLibraryDescription.getUntypedBuildTarget(buildTarget);
BuildTarget headerSymlinkTreeTarget =
CxxDescriptionEnhancer.createSandboxSymlinkTreeTarget(
untypedTarget, cxxPlatform.getFlavor());
BuildRule rule = ruleResolver.requireRule(headerSymlinkTreeTarget);
Preconditions.checkState(
rule instanceof SymlinkTree, rule.getBuildTarget() + " " + rule.getClass().toString());
return (SymlinkTree) rule;
}
/**
* @return the {@link BuildTarget} to use for the {@link BuildRule} generating the symlink tree of
* headers.
*/
@VisibleForTesting
public static BuildTarget createHeaderSymlinkTreeTarget(
BuildTarget target, HeaderVisibility headerVisibility, Flavor... flavors) {
return BuildTarget.builder(target)
.addFlavors(getHeaderSymlinkTreeFlavor(headerVisibility))
.addFlavors(flavors)
.build();
}
@VisibleForTesting
public static BuildTarget createSandboxSymlinkTreeTarget(BuildTarget target, Flavor platform) {
return BuildTarget.builder(target).addFlavors(platform).addFlavors(SANDBOX_TREE_FLAVOR).build();
}
/** @return the absolute {@link Path} to use for the symlink tree of headers. */
public static Path getHeaderSymlinkTreePath(
ProjectFilesystem filesystem,
BuildTarget target,
HeaderVisibility headerVisibility,
Flavor... flavors) {
return BuildTargets.getGenPath(
filesystem, createHeaderSymlinkTreeTarget(target, headerVisibility, flavors), "%s");
}
public static Path getSandboxSymlinkTreePath(ProjectFilesystem filesystem, BuildTarget target) {
return BuildTargets.getGenPath(filesystem, target, "%s");
}
public static Flavor getHeaderSymlinkTreeFlavor(HeaderVisibility headerVisibility) {
switch (headerVisibility) {
case PUBLIC:
return EXPORTED_HEADER_SYMLINK_TREE_FLAVOR;
case PRIVATE:
return HEADER_SYMLINK_TREE_FLAVOR;
default:
throw new RuntimeException("Unexpected value of enum ExportMode");
}
}
static ImmutableMap<String, SourcePath> parseOnlyHeaders(
BuildTarget buildTarget,
SourcePathRuleFinder ruleFinder,
SourcePathResolver sourcePathResolver,
String parameterName,
SourceList exportedHeaders) {
return exportedHeaders.toNameMap(
buildTarget,
sourcePathResolver,
parameterName,
path -> !CxxGenruleDescription.wrapsCxxGenrule(ruleFinder, path),
path -> path);
}
static ImmutableMap<String, SourcePath> parseOnlyPlatformHeaders(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver sourcePathResolver,
CxxPlatform cxxPlatform,
String headersParameterName,
SourceList headers,
String platformHeadersParameterName,
PatternMatchedCollection<SourceList> platformHeaders)
throws NoSuchBuildTargetException {
ImmutableMap.Builder<String, SourcePath> parsed = ImmutableMap.builder();
java.util.function.Function<SourcePath, SourcePath> fixup =
path -> {
try {
return CxxGenruleDescription.fixupSourcePath(resolver, ruleFinder, cxxPlatform, path);
} catch (NoSuchBuildTargetException e) {
throw new RuntimeException(e);
}
};
// Include all normal exported headers that are generated by `cxx_genrule`.
parsed.putAll(
headers.toNameMap(
buildTarget,
sourcePathResolver,
headersParameterName,
path -> CxxGenruleDescription.wrapsCxxGenrule(ruleFinder, path),
fixup));
// Include all platform specific headers.
for (SourceList sourceList :
platformHeaders.getMatchingValues(cxxPlatform.getFlavor().toString())) {
parsed.putAll(
sourceList.toNameMap(
buildTarget, sourcePathResolver, platformHeadersParameterName, path -> true, fixup));
}
return parsed.build();
}
/**
* @return a map of header locations to input {@link SourcePath} objects formed by parsing the
* input {@link SourcePath} objects for the "headers" parameter.
*/
public static ImmutableMap<Path, SourcePath> parseHeaders(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver sourcePathResolver,
Optional<CxxPlatform> cxxPlatform,
CxxConstructorArg args)
throws NoSuchBuildTargetException {
ImmutableMap.Builder<String, SourcePath> headers = ImmutableMap.builder();
// Add platform-agnostic headers.
headers.putAll(
parseOnlyHeaders(
buildTarget, ruleFinder, sourcePathResolver, "headers", args.getHeaders()));
// Add platform-specific headers.
if (cxxPlatform.isPresent()) {
headers.putAll(
parseOnlyPlatformHeaders(
buildTarget,
resolver,
ruleFinder,
sourcePathResolver,
cxxPlatform.get(),
"headers",
args.getHeaders(),
"platform_headers",
args.getPlatformHeaders()));
}
return CxxPreprocessables.resolveHeaderMap(
args.getHeaderNamespace().map(Paths::get).orElse(buildTarget.getBasePath()),
headers.build());
}
/**
* @return a map of header locations to input {@link SourcePath} objects formed by parsing the
* input {@link SourcePath} objects for the "exportedHeaders" parameter.
*/
public static ImmutableMap<Path, SourcePath> parseExportedHeaders(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver sourcePathResolver,
Optional<CxxPlatform> cxxPlatform,
CxxLibraryDescription.CommonArg args)
throws NoSuchBuildTargetException {
ImmutableMap.Builder<String, SourcePath> headers = ImmutableMap.builder();
// Include platform-agnostic headers.
headers.putAll(
parseOnlyHeaders(
buildTarget,
ruleFinder,
sourcePathResolver,
"exported_headers",
args.getExportedHeaders()));
// If a platform is specific, include platform-specific headers.
if (cxxPlatform.isPresent()) {
headers.putAll(
parseOnlyPlatformHeaders(
buildTarget,
resolver,
ruleFinder,
sourcePathResolver,
cxxPlatform.get(),
"exported_headers",
args.getExportedHeaders(),
"exported_platform_headers",
args.getExportedPlatformHeaders()));
}
return CxxPreprocessables.resolveHeaderMap(
args.getHeaderNamespace().map(Paths::get).orElse(buildTarget.getBasePath()),
headers.build());
}
/**
* @return a map of header locations to input {@link SourcePath} objects formed by parsing the
* input {@link SourcePath} objects for the "exportedHeaders" parameter.
*/
public static ImmutableMap<Path, SourcePath> parseExportedPlatformHeaders(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver sourcePathResolver,
CxxPlatform cxxPlatform,
CxxLibraryDescription.CommonArg args)
throws NoSuchBuildTargetException {
return CxxPreprocessables.resolveHeaderMap(
args.getHeaderNamespace().map(Paths::get).orElse(buildTarget.getBasePath()),
parseOnlyPlatformHeaders(
buildTarget,
resolver,
ruleFinder,
sourcePathResolver,
cxxPlatform,
"exported_headers",
args.getExportedHeaders(),
"exported_platform_headers",
args.getExportedPlatformHeaders()));
}
/**
* @return a list {@link CxxSource} objects formed by parsing the input {@link SourcePath} objects
* for the "srcs" parameter.
*/
public static ImmutableMap<String, CxxSource> parseCxxSources(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver pathResolver,
CxxPlatform cxxPlatform,
CxxConstructorArg args) {
return parseCxxSources(
buildTarget,
resolver,
ruleFinder,
pathResolver,
cxxPlatform,
args.getSrcs(),
args.getPlatformSrcs());
}
public static ImmutableMap<String, CxxSource> parseCxxSources(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver pathResolver,
CxxPlatform cxxPlatform,
ImmutableSortedSet<SourceWithFlags> srcs,
PatternMatchedCollection<ImmutableSortedSet<SourceWithFlags>> platformSrcs) {
ImmutableMap.Builder<String, SourceWithFlags> sources = ImmutableMap.builder();
putAllSources(buildTarget, resolver, ruleFinder, pathResolver, cxxPlatform, srcs, sources);
for (ImmutableSortedSet<SourceWithFlags> sourcesWithFlags :
platformSrcs.getMatchingValues(cxxPlatform.getFlavor().toString())) {
putAllSources(
buildTarget, resolver, ruleFinder, pathResolver, cxxPlatform, sourcesWithFlags, sources);
}
return resolveCxxSources(sources.build());
}
private static void putAllSources(
BuildTarget buildTarget,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
SourcePathResolver pathResolver,
CxxPlatform cxxPlatform,
ImmutableSortedSet<SourceWithFlags> sourcesWithFlags,
ImmutableMap.Builder<String, SourceWithFlags> sources) {
sources.putAll(
pathResolver.getSourcePathNames(
buildTarget,
"srcs",
sourcesWithFlags
.stream()
.map(
s -> {
try {
return s.withSourcePath(
CxxGenruleDescription.fixupSourcePath(
resolver,
ruleFinder,
cxxPlatform,
Preconditions.checkNotNull(s.getSourcePath())));
} catch (NoSuchBuildTargetException e) {
throw new RuntimeException(e);
}
})
.collect(MoreCollectors.toImmutableList()),
x -> true,
SourceWithFlags::getSourcePath));
}
public static ImmutableList<CxxPreprocessorInput> collectCxxPreprocessorInput(
BuildTarget target,
CxxPlatform cxxPlatform,
Iterable<BuildRule> deps,
ImmutableMultimap<CxxSource.Type, String> preprocessorFlags,
ImmutableList<HeaderSymlinkTree> headerSymlinkTrees,
ImmutableSet<FrameworkPath> frameworks,
Iterable<CxxPreprocessorInput> cxxPreprocessorInputFromDeps,
ImmutableList<String> includeDirs,
Optional<SymlinkTree> symlinkTree)
throws NoSuchBuildTargetException {
// Add the private includes of any rules which this rule depends on, and which list this rule as
// a test.
BuildTarget targetWithoutFlavor = BuildTarget.of(target.getUnflavoredBuildTarget());
ImmutableList.Builder<CxxPreprocessorInput> cxxPreprocessorInputFromTestedRulesBuilder =
ImmutableList.builder();
for (BuildRule rule : deps) {
if (rule instanceof NativeTestable) {
NativeTestable testable = (NativeTestable) rule;
if (testable.isTestedBy(targetWithoutFlavor)) {
LOG.debug(
"Adding private includes of tested rule %s to testing rule %s",
rule.getBuildTarget(), target);
cxxPreprocessorInputFromTestedRulesBuilder.add(
testable.getPrivateCxxPreprocessorInput(cxxPlatform));
// Add any dependent headers
cxxPreprocessorInputFromTestedRulesBuilder.addAll(
CxxPreprocessables.getTransitiveCxxPreprocessorInput(
cxxPlatform, ImmutableList.of(rule)));
}
}
}
ImmutableList<CxxPreprocessorInput> cxxPreprocessorInputFromTestedRules =
cxxPreprocessorInputFromTestedRulesBuilder.build();
LOG.verbose(
"Rules tested by target %s added private includes %s",
target, cxxPreprocessorInputFromTestedRules);
ImmutableList.Builder<CxxHeaders> allIncludes = ImmutableList.builder();
for (HeaderSymlinkTree headerSymlinkTree : headerSymlinkTrees) {
allIncludes.add(
CxxSymlinkTreeHeaders.from(headerSymlinkTree, CxxPreprocessables.IncludeType.LOCAL));
}
CxxPreprocessorInput.Builder builder = CxxPreprocessorInput.builder();
builder.putAllPreprocessorFlags(preprocessorFlags);
// headers from #sandbox are put before #private-headers and #headers on purpose
// this is the only way to control windows behavior
if (symlinkTree.isPresent()) {
for (String includeDir : includeDirs) {
builder.addIncludes(
CxxSandboxInclude.from(
symlinkTree.get(), includeDir, CxxPreprocessables.IncludeType.LOCAL));
}
}
builder.addAllIncludes(allIncludes.build()).addAllFrameworks(frameworks);
CxxPreprocessorInput localPreprocessorInput = builder.build();
return ImmutableList.<CxxPreprocessorInput>builder()
.add(localPreprocessorInput)
.addAll(cxxPreprocessorInputFromDeps)
.addAll(cxxPreprocessorInputFromTestedRules)
.build();
}
public static BuildTarget createStaticLibraryBuildTarget(
BuildTarget target, Flavor platform, CxxSourceRuleFactory.PicType pic) {
return BuildTarget.builder(target)
.addFlavors(platform)
.addFlavors(pic == CxxSourceRuleFactory.PicType.PDC ? STATIC_FLAVOR : STATIC_PIC_FLAVOR)
.build();
}
public static BuildTarget createSharedLibraryBuildTarget(
BuildTarget target, Flavor platform, Linker.LinkType linkType) {
Flavor linkFlavor;
switch (linkType) {
case SHARED:
linkFlavor = SHARED_FLAVOR;
break;
case MACH_O_BUNDLE:
linkFlavor = MACH_O_BUNDLE_FLAVOR;
break;
case EXECUTABLE:
default:
throw new IllegalStateException(
"Only SHARED and MACH_O_BUNDLE types expected, got: " + linkType);
}
return BuildTarget.builder(target).addFlavors(platform).addFlavors(linkFlavor).build();
}
public static Path getStaticLibraryPath(
ProjectFilesystem filesystem,
BuildTarget target,
Flavor platform,
CxxSourceRuleFactory.PicType pic,
String extension) {
return getStaticLibraryPath(filesystem, target, platform, pic, extension, "");
}
public static Path getStaticLibraryPath(
ProjectFilesystem filesystem,
BuildTarget target,
Flavor platform,
CxxSourceRuleFactory.PicType pic,
String extension,
String suffix) {
String name = String.format("lib%s%s.%s", target.getShortName(), suffix, extension);
return BuildTargets.getGenPath(
filesystem, createStaticLibraryBuildTarget(target, platform, pic), "%s")
.resolve(name);
}
public static String getSharedLibrarySoname(
Optional<String> declaredSoname, BuildTarget target, CxxPlatform platform) {
if (!declaredSoname.isPresent()) {
return getDefaultSharedLibrarySoname(target, platform);
}
return getNonDefaultSharedLibrarySoname(
declaredSoname.get(),
platform.getSharedLibraryExtension(),
platform.getSharedLibraryVersionedExtensionFormat());
}
@VisibleForTesting
static String getNonDefaultSharedLibrarySoname(
String declared,
String sharedLibraryExtension,
String sharedLibraryVersionedExtensionFormat) {
Matcher match = SONAME_EXT_MACRO_PATTERN.matcher(declared);
if (!match.find()) {
return declared;
}
String version = match.group(1);
if (version == null) {
return match.replaceFirst(sharedLibraryExtension);
}
return match.replaceFirst(String.format(sharedLibraryVersionedExtensionFormat, version));
}
public static String getDefaultSharedLibrarySoname(BuildTarget target, CxxPlatform platform) {
String libName =
Joiner.on('_')
.join(
ImmutableList.builder()
.addAll(
StreamSupport.stream(target.getBasePath().spliterator(), false)
.map(Object::toString)
.filter(x -> !x.isEmpty())
.iterator())
.add(target.getShortName())
.build());
String extension = platform.getSharedLibraryExtension();
return String.format("lib%s.%s", libName, extension);
}
public static Path getSharedLibraryPath(
ProjectFilesystem filesystem, BuildTarget sharedLibraryTarget, String soname) {
return BuildTargets.getGenPath(filesystem, sharedLibraryTarget, "%s/" + soname);
}
private static Path getBinaryOutputPath(
BuildTarget target, ProjectFilesystem filesystem, Optional<String> extension) {
String format = extension.map(ext -> "%s." + ext).orElse("%s");
return BuildTargets.getGenPath(filesystem, target, format);
}
@VisibleForTesting
public static BuildTarget createCxxLinkTarget(
BuildTarget target, Optional<LinkerMapMode> flavoredLinkerMapMode) {
if (flavoredLinkerMapMode.isPresent()) {
target = target.withAppendedFlavors(flavoredLinkerMapMode.get().getFlavor());
}
return target.withAppendedFlavors(CXX_LINK_BINARY_FLAVOR);
}
/**
* @return a function that transforms the {@link FrameworkPath} to search paths with any embedded
* macros expanded.
*/
public static RuleKeyAppendableFunction<FrameworkPath, Path> frameworkPathToSearchPath(
final CxxPlatform cxxPlatform, final SourcePathResolver resolver) {
return new RuleKeyAppendableFunction<FrameworkPath, Path>() {
private RuleKeyAppendableFunction<String, String> translateMacrosFn =
CxxFlags.getTranslateMacrosFn(cxxPlatform);
@Override
public void appendToRuleKey(RuleKeyObjectSink sink) {
sink.setReflectively("translateMacrosFn", translateMacrosFn);
}
@Override
public Path apply(FrameworkPath input) {
String pathAsString =
FrameworkPath.getUnexpandedSearchPath(
resolver::getAbsolutePath, Functions.identity(), input)
.toString();
return Paths.get(translateMacrosFn.apply(pathAsString));
}
};
}
public static CxxLinkAndCompileRules createBuildRulesForCxxBinaryDescriptionArg(
TargetGraph targetGraph,
BuildRuleParams params,
BuildRuleResolver resolver,
CellPathResolver cellRoots,
CxxBuckConfig cxxBuckConfig,
CxxPlatform cxxPlatform,
CxxBinaryDescription.CommonArg args,
ImmutableSet<BuildTarget> extraDeps,
Optional<StripStyle> stripStyle,
Optional<LinkerMapMode> flavoredLinkerMapMode)
throws NoSuchBuildTargetException {
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
ImmutableMap<String, CxxSource> srcs =
parseCxxSources(
params.getBuildTarget(), resolver, ruleFinder, pathResolver, cxxPlatform, args);
ImmutableMap<Path, SourcePath> headers =
parseHeaders(
params.getBuildTarget(),
resolver,
ruleFinder,
pathResolver,
Optional.of(cxxPlatform),
args);
// Build the binary deps.
ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder();
// Add original declared and extra deps.
args.getCxxDeps().get(resolver, cxxPlatform).forEach(depsBuilder::add);
// Add in deps found via deps query.
args.getDepsQuery()
.ifPresent(
query ->
QueryUtils.resolveDepQuery(
params.getBuildTarget(),
query,
resolver,
cellRoots,
targetGraph,
args.getDeps())
.forEach(depsBuilder::add));
// Add any extra deps passed in.
extraDeps.stream().map(resolver::getRule).forEach(depsBuilder::add);
ImmutableSortedSet<BuildRule> deps = depsBuilder.build();
return createBuildRulesForCxxBinary(
params,
resolver,
cellRoots,
cxxBuckConfig,
cxxPlatform,
srcs,
headers,
deps,
stripStyle,
flavoredLinkerMapMode,
args.getLinkStyle().orElse(Linker.LinkableDepType.STATIC),
args.getThinLto(),
args.getPreprocessorFlags(),
args.getPlatformPreprocessorFlags(),
args.getLangPreprocessorFlags(),
args.getFrameworks(),
args.getLibraries(),
args.getCompilerFlags(),
args.getLangCompilerFlags(),
args.getPlatformCompilerFlags(),
args.getPrefixHeader(),
args.getPrecompiledHeader(),
args.getLinkerFlags(),
args.getPlatformLinkerFlags(),
args.getCxxRuntimeType(),
args.getIncludeDirs(),
Optional.empty());
}
public static CxxLinkAndCompileRules createBuildRulesForCxxBinary(
BuildRuleParams params,
BuildRuleResolver resolver,
CellPathResolver cellRoots,
CxxBuckConfig cxxBuckConfig,
CxxPlatform cxxPlatform,
ImmutableMap<String, CxxSource> srcs,
ImmutableMap<Path, SourcePath> headers,
SortedSet<BuildRule> deps,
Optional<StripStyle> stripStyle,
Optional<LinkerMapMode> flavoredLinkerMapMode,
Linker.LinkableDepType linkStyle,
boolean thinLto,
ImmutableList<String> preprocessorFlags,
PatternMatchedCollection<ImmutableList<String>> platformPreprocessorFlags,
ImmutableMap<CxxSource.Type, ImmutableList<String>> langPreprocessorFlags,
ImmutableSortedSet<FrameworkPath> frameworks,
ImmutableSortedSet<FrameworkPath> libraries,
ImmutableList<String> compilerFlags,
ImmutableMap<CxxSource.Type, ImmutableList<String>> langCompilerFlags,
PatternMatchedCollection<ImmutableList<String>> platformCompilerFlags,
Optional<SourcePath> prefixHeader,
Optional<SourcePath> precompiledHeader,
ImmutableList<StringWithMacros> linkerFlags,
PatternMatchedCollection<ImmutableList<StringWithMacros>> platformLinkerFlags,
Optional<Linker.CxxRuntimeType> cxxRuntimeType,
ImmutableList<String> includeDirs,
Optional<Boolean> xcodePrivateHeadersSymlinks)
throws NoSuchBuildTargetException {
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
SourcePathResolver sourcePathResolver = new SourcePathResolver(ruleFinder);
// TODO(beefon): should be:
// Path linkOutput = getLinkOutputPath(
// createCxxLinkTarget(params.getBuildTarget(), flavoredLinkerMapMode),
// params.getProjectFilesystem());
BuildTarget target = params.getBuildTarget();
if (flavoredLinkerMapMode.isPresent()) {
target = target.withAppendedFlavors(flavoredLinkerMapMode.get().getFlavor());
}
Path linkOutput =
getBinaryOutputPath(
target, params.getProjectFilesystem(), cxxPlatform.getBinaryExtension());
ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();
CommandTool.Builder executableBuilder = new CommandTool.Builder();
// Setup the header symlink tree and combine all the preprocessor input from this rule
// and all dependencies.
boolean shouldCreatePrivateHeadersSymlinks =
xcodePrivateHeadersSymlinks.orElse(cxxBuckConfig.getPrivateHeadersSymlinksEnabled());
HeaderSymlinkTree headerSymlinkTree =
requireHeaderSymlinkTree(
params.getBuildTarget(),
params.getProjectFilesystem(),
resolver,
cxxPlatform,
headers,
HeaderVisibility.PRIVATE,
shouldCreatePrivateHeadersSymlinks);
Optional<SymlinkTree> sandboxTree = Optional.empty();
if (cxxBuckConfig.sandboxSources()) {
sandboxTree = createSandboxTree(params.getBuildTarget(), resolver, cxxPlatform);
}
ImmutableList<CxxPreprocessorInput> cxxPreprocessorInput =
collectCxxPreprocessorInput(
params.getBuildTarget(),
cxxPlatform,
deps,
CxxFlags.getLanguageFlags(
preprocessorFlags, platformPreprocessorFlags, langPreprocessorFlags, cxxPlatform),
ImmutableList.of(headerSymlinkTree),
frameworks,
CxxPreprocessables.getTransitiveCxxPreprocessorInput(
cxxPlatform,
RichStream.from(deps)
.filter(CxxPreprocessorDep.class::isInstance)
.toImmutableList()),
includeDirs,
sandboxTree);
ImmutableList.Builder<String> compilerFlagsWithLto = ImmutableList.builder();
compilerFlagsWithLto.addAll(compilerFlags);
if (thinLto) {
compilerFlagsWithLto.add("-flto=thin");
}
// Generate and add all the build rules to preprocess and compile the source to the
// resolver and get the `SourcePath`s representing the generated object files.
ImmutableMap<CxxPreprocessAndCompile, SourcePath> objects =
CxxSourceRuleFactory.requirePreprocessAndCompileRules(
params.getProjectFilesystem(),
params.getBuildTarget(),
resolver,
sourcePathResolver,
ruleFinder,
cxxBuckConfig,
cxxPlatform,
cxxPreprocessorInput,
CxxFlags.getLanguageFlags(
compilerFlagsWithLto.build(),
platformCompilerFlags,
langCompilerFlags,
cxxPlatform),
prefixHeader,
precompiledHeader,
srcs,
linkStyle == Linker.LinkableDepType.STATIC
? CxxSourceRuleFactory.PicType.PDC
: CxxSourceRuleFactory.PicType.PIC,
sandboxTree);
// Build up the linker flags, which support macro expansion.
argsBuilder.addAll(
toStringWithMacrosArgs(
target,
cellRoots,
resolver,
cxxPlatform,
CxxFlags.getFlagsWithMacrosWithPlatformMacroExpansion(
linkerFlags, platformLinkerFlags, cxxPlatform)));
// Special handling for dynamically linked binaries.
if (linkStyle == Linker.LinkableDepType.SHARED) {
// Create a symlink tree with for all shared libraries needed by this binary.
SymlinkTree sharedLibraries =
requireSharedLibrarySymlinkTree(
params.getBuildTarget(),
params.getProjectFilesystem(),
resolver,
ruleFinder,
cxxPlatform,
deps,
NativeLinkable.class::isInstance);
// Embed a origin-relative library path into the binary so it can find the shared libraries.
// The shared libraries root is absolute. Also need an absolute path to the linkOutput
Path absLinkOut = params.getBuildTarget().getCellPath().resolve(linkOutput);
argsBuilder.addAll(
StringArg.from(
Linkers.iXlinker(
"-rpath",
String.format(
"%s/%s",
cxxPlatform.getLd().resolve(resolver).origin(),
absLinkOut.getParent().relativize(sharedLibraries.getRoot()).toString()))));
// Add all the shared libraries and the symlink tree as inputs to the tool that represents
// this binary, so that users can attach the proper deps.
executableBuilder.addDep(sharedLibraries);
executableBuilder.addInputs(sharedLibraries.getLinks().values());
}
// Add object files into the args.
ImmutableList<SourcePathArg> objectArgs =
SourcePathArg.from(objects.values())
.stream()
.map(
input -> {
Preconditions.checkArgument(input instanceof SourcePathArg);
return (SourcePathArg) input;
})
.collect(MoreCollectors.toImmutableList());
argsBuilder.addAll(FileListableLinkerInputArg.from(objectArgs));
BuildTarget linkRuleTarget =
createCxxLinkTarget(params.getBuildTarget(), flavoredLinkerMapMode);
CxxLink cxxLink =
createCxxLinkRule(
params,
resolver,
cxxBuckConfig,
cxxPlatform,
RichStream.from(deps).filter(NativeLinkable.class).toImmutableList(),
linkStyle,
thinLto,
frameworks,
libraries,
cxxRuntimeType,
sourcePathResolver,
ruleFinder,
linkOutput,
argsBuilder,
linkRuleTarget);
BuildRule binaryRuleForExecutable;
Optional<CxxStrip> cxxStrip = Optional.empty();
if (stripStyle.isPresent()) {
BuildRuleParams cxxParams = params;
if (flavoredLinkerMapMode.isPresent()) {
cxxParams = params.withAppendedFlavor(flavoredLinkerMapMode.get().getFlavor());
}
CxxStrip stripRule =
createCxxStripRule(cxxParams, resolver, stripStyle.get(), cxxLink, cxxPlatform);
cxxStrip = Optional.of(stripRule);
binaryRuleForExecutable = stripRule;
} else {
binaryRuleForExecutable = cxxLink;
}
// Add the output of the link as the lone argument needed to invoke this binary as a tool.
executableBuilder.addArg(SourcePathArg.of(binaryRuleForExecutable.getSourcePathToOutput()));
return new CxxLinkAndCompileRules(
cxxLink,
cxxStrip,
ImmutableSortedSet.copyOf(objects.keySet()),
executableBuilder.build(),
deps);
}
private static CxxLink createCxxLinkRule(
BuildRuleParams params,
BuildRuleResolver resolver,
CxxBuckConfig cxxBuckConfig,
CxxPlatform cxxPlatform,
Iterable<? extends NativeLinkable> deps,
Linker.LinkableDepType linkStyle,
boolean thinLto,
ImmutableSortedSet<FrameworkPath> frameworks,
ImmutableSortedSet<FrameworkPath> libraries,
Optional<Linker.CxxRuntimeType> cxxRuntimeType,
SourcePathResolver sourcePathResolver,
SourcePathRuleFinder ruleFinder,
Path linkOutput,
ImmutableList.Builder<Arg> argsBuilder,
BuildTarget linkRuleTarget)
throws NoSuchBuildTargetException {
CxxLink cxxLink;
Optional<BuildRule> existingCxxLinkRule = resolver.getRuleOptional(linkRuleTarget);
if (existingCxxLinkRule.isPresent()) {
Preconditions.checkArgument(existingCxxLinkRule.get() instanceof CxxLink);
cxxLink = (CxxLink) existingCxxLinkRule.get();
} else {
// Generate the final link rule. We use the top-level target as the link rule's
// target, so that it corresponds to the actual binary we build.
cxxLink =
CxxLinkableEnhancer.createCxxLinkableBuildRule(
cxxBuckConfig,
cxxPlatform,
params,
resolver,
sourcePathResolver,
ruleFinder,
linkRuleTarget,
Linker.LinkType.EXECUTABLE,
Optional.empty(),
linkOutput,
linkStyle,
thinLto,
deps,
cxxRuntimeType,
Optional.empty(),
ImmutableSet.of(),
NativeLinkableInput.builder()
.setArgs(argsBuilder.build())
.setFrameworks(frameworks)
.setLibraries(libraries)
.build(),
Optional.empty());
resolver.addToIndex(cxxLink);
}
return cxxLink;
}
public static CxxStrip createCxxStripRule(
BuildRuleParams params,
BuildRuleResolver resolver,
StripStyle stripStyle,
BuildRule unstrippedBinaryRule,
CxxPlatform cxxPlatform) {
BuildRuleParams stripRuleParams =
params
.withBuildTarget(
params
.getBuildTarget()
.withAppendedFlavors(CxxStrip.RULE_FLAVOR, stripStyle.getFlavor()))
.copyReplacingDeclaredAndExtraDeps(
ImmutableSortedSet.of(unstrippedBinaryRule), ImmutableSortedSet.of());
Optional<BuildRule> exisitingRule = resolver.getRuleOptional(stripRuleParams.getBuildTarget());
if (exisitingRule.isPresent()) {
Preconditions.checkArgument(exisitingRule.get() instanceof CxxStrip);
return (CxxStrip) exisitingRule.get();
} else {
CxxStrip cxxStrip =
new CxxStrip(
stripRuleParams,
stripStyle,
Preconditions.checkNotNull(unstrippedBinaryRule.getSourcePathToOutput()),
cxxPlatform.getStrip(),
CxxDescriptionEnhancer.getBinaryOutputPath(
stripRuleParams.getBuildTarget(),
params.getProjectFilesystem(),
cxxPlatform.getBinaryExtension()));
resolver.addToIndex(cxxStrip);
return cxxStrip;
}
}
public static BuildRule createUberCompilationDatabase(
BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleResolver ruleResolver)
throws NoSuchBuildTargetException {
Optional<CxxCompilationDatabaseDependencies> compilationDatabases =
ruleResolver.requireMetadata(
buildTarget
.withoutFlavors(CxxCompilationDatabase.UBER_COMPILATION_DATABASE)
.withAppendedFlavors(CxxCompilationDatabase.COMPILATION_DATABASE),
CxxCompilationDatabaseDependencies.class);
Preconditions.checkState(compilationDatabases.isPresent());
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver);
SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
return new JsonConcatenate(
new BuildRuleParams(
buildTarget,
() ->
ImmutableSortedSet.copyOf(
ruleFinder.filterBuildRuleInputs(compilationDatabases.get().getSourcePaths())),
() -> ImmutableSortedSet.of(),
ImmutableSortedSet.of(),
projectFilesystem),
pathResolver.getAllAbsolutePaths(compilationDatabases.get().getSourcePaths()),
"compilation-database-concatenate",
"Concatenate compilation databases",
"uber-compilation-database",
"compile_commands.json");
}
public static Optional<CxxCompilationDatabaseDependencies> createCompilationDatabaseDependencies(
BuildTarget buildTarget,
FlavorDomain<CxxPlatform> platforms,
BuildRuleResolver resolver,
CxxConstructorArg args)
throws NoSuchBuildTargetException {
Preconditions.checkState(
buildTarget.getFlavors().contains(CxxCompilationDatabase.COMPILATION_DATABASE));
Optional<Flavor> cxxPlatformFlavor = platforms.getFlavor(buildTarget);
Preconditions.checkState(
cxxPlatformFlavor.isPresent(),
"Could not find cxx platform in:\n%s",
Joiner.on(", ").join(buildTarget.getFlavors()));
ImmutableSet.Builder<SourcePath> sourcePaths = ImmutableSet.builder();
for (BuildTarget dep : args.getDeps()) {
Optional<CxxCompilationDatabaseDependencies> compilationDatabases =
resolver.requireMetadata(
BuildTarget.builder(dep)
.addFlavors(CxxCompilationDatabase.COMPILATION_DATABASE)
.addFlavors(cxxPlatformFlavor.get())
.build(),
CxxCompilationDatabaseDependencies.class);
if (compilationDatabases.isPresent()) {
sourcePaths.addAll(compilationDatabases.get().getSourcePaths());
}
}
// Not all parts of Buck use require yet, so require the rule here so it's available in the
// resolver for the parts that don't.
BuildRule buildRule = resolver.requireRule(buildTarget);
sourcePaths.add(buildRule.getSourcePathToOutput());
return Optional.of(CxxCompilationDatabaseDependencies.of(sourcePaths.build()));
}
public static Optional<SymlinkTree> createSandboxTree(
BuildTarget buildTarget, BuildRuleResolver ruleResolver, CxxPlatform cxxPlatform)
throws NoSuchBuildTargetException {
return Optional.of(requireSandboxSymlinkTree(buildTarget, ruleResolver, cxxPlatform));
}
/**
* @return the {@link BuildTarget} to use for the {@link BuildRule} generating the symlink tree of
* shared libraries.
*/
public static BuildTarget createSharedLibrarySymlinkTreeTarget(
BuildTarget target, Flavor platform) {
return BuildTarget.builder(target)
.addFlavors(SHARED_LIBRARY_SYMLINK_TREE_FLAVOR)
.addFlavors(platform)
.build();
}
/** @return the {@link Path} to use for the symlink tree of headers. */
public static Path getSharedLibrarySymlinkTreePath(
ProjectFilesystem filesystem, BuildTarget target, Flavor platform) {
return BuildTargets.getGenPath(
filesystem, createSharedLibrarySymlinkTreeTarget(target, platform), "%s");
}
/**
* Build a {@link HeaderSymlinkTree} of all the shared libraries found via the top-level rule's
* transitive dependencies.
*/
public static SymlinkTree createSharedLibrarySymlinkTree(
SourcePathRuleFinder ruleFinder,
BuildTarget baseBuildTarget,
ProjectFilesystem filesystem,
CxxPlatform cxxPlatform,
Iterable<? extends BuildRule> deps,
Predicate<Object> traverse,
Predicate<Object> skip)
throws NoSuchBuildTargetException {
BuildTarget symlinkTreeTarget =
createSharedLibrarySymlinkTreeTarget(baseBuildTarget, cxxPlatform.getFlavor());
Path symlinkTreeRoot =
getSharedLibrarySymlinkTreePath(filesystem, baseBuildTarget, cxxPlatform.getFlavor());
ImmutableSortedMap<String, SourcePath> libraries =
NativeLinkables.getTransitiveSharedLibraries(cxxPlatform, deps, traverse, skip);
ImmutableMap.Builder<Path, SourcePath> links = ImmutableMap.builder();
for (Map.Entry<String, SourcePath> ent : libraries.entrySet()) {
links.put(Paths.get(ent.getKey()), ent.getValue());
}
return new SymlinkTree(
symlinkTreeTarget, filesystem, symlinkTreeRoot, links.build(), ruleFinder);
}
public static SymlinkTree createSharedLibrarySymlinkTree(
SourcePathRuleFinder ruleFinder,
BuildTarget baseBuildTarget,
ProjectFilesystem filesystem,
CxxPlatform cxxPlatform,
Iterable<? extends BuildRule> deps,
Predicate<Object> traverse)
throws NoSuchBuildTargetException {
return createSharedLibrarySymlinkTree(
ruleFinder, baseBuildTarget, filesystem, cxxPlatform, deps, traverse, x -> false);
}
public static SymlinkTree requireSharedLibrarySymlinkTree(
BuildTarget buildTarget,
ProjectFilesystem filesystem,
BuildRuleResolver resolver,
SourcePathRuleFinder ruleFinder,
CxxPlatform cxxPlatform,
Iterable<? extends BuildRule> deps,
Predicate<Object> traverse)
throws NoSuchBuildTargetException {
BuildTarget target = createSharedLibrarySymlinkTreeTarget(buildTarget, cxxPlatform.getFlavor());
SymlinkTree tree = resolver.getRuleOptionalWithType(target, SymlinkTree.class).orElse(null);
if (tree == null) {
tree =
resolver.addToIndex(
createSharedLibrarySymlinkTree(
ruleFinder, buildTarget, filesystem, cxxPlatform, deps, traverse));
}
return tree;
}
public static Flavor flavorForLinkableDepType(Linker.LinkableDepType linkableDepType) {
switch (linkableDepType) {
case STATIC:
return STATIC_FLAVOR;
case STATIC_PIC:
return STATIC_PIC_FLAVOR;
case SHARED:
return SHARED_FLAVOR;
}
throw new RuntimeException(String.format("Unsupported LinkableDepType: '%s'", linkableDepType));
}
public static SymlinkTree createSandboxTreeBuildRule(
BuildRuleResolver resolver,
CxxConstructorArg args,
CxxPlatform platform,
BuildRuleParams params)
throws NoSuchBuildTargetException {
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
SourcePathResolver sourcePathResolver = new SourcePathResolver(ruleFinder);
ImmutableCollection<SourcePath> privateHeaders =
parseHeaders(
params.getBuildTarget(),
resolver,
ruleFinder,
sourcePathResolver,
Optional.of(platform),
args)
.values();
ImmutableCollection<CxxSource> sources =
parseCxxSources(
params.getBuildTarget(), resolver, ruleFinder, sourcePathResolver, platform, args)
.values();
HashMap<Path, SourcePath> links = new HashMap<>();
for (SourcePath headerPath : privateHeaders) {
links.put(
Paths.get(sourcePathResolver.getSourcePathName(params.getBuildTarget(), headerPath)),
headerPath);
}
if (args instanceof CxxLibraryDescription.CommonArg) {
ImmutableCollection<SourcePath> publicHeaders =
CxxDescriptionEnhancer.parseExportedHeaders(
params.getBuildTarget(),
resolver,
ruleFinder,
sourcePathResolver,
Optional.of(platform),
(CxxLibraryDescription.CommonArg) args)
.values();
for (SourcePath headerPath : publicHeaders) {
links.put(
Paths.get(sourcePathResolver.getSourcePathName(params.getBuildTarget(), headerPath)),
headerPath);
}
}
for (CxxSource source : sources) {
SourcePath sourcePath = source.getPath();
links.put(
Paths.get(sourcePathResolver.getSourcePathName(params.getBuildTarget(), sourcePath)),
sourcePath);
}
return createSandboxSymlinkTree(params, platform, ImmutableMap.copyOf(links), ruleFinder);
}
/** Resolve the map of names to SourcePaths to a map of names to CxxSource objects. */
private static ImmutableMap<String, CxxSource> resolveCxxSources(
ImmutableMap<String, SourceWithFlags> sources) {
ImmutableMap.Builder<String, CxxSource> cxxSources = ImmutableMap.builder();
// For each entry in the input C/C++ source, build a CxxSource object to wrap
// it's name, input path, and output object file path.
for (ImmutableMap.Entry<String, SourceWithFlags> ent : sources.entrySet()) {
String extension = Files.getFileExtension(ent.getKey());
Optional<CxxSource.Type> type = CxxSource.Type.fromExtension(extension);
if (!type.isPresent()) {
throw new HumanReadableException("invalid extension \"%s\": %s", extension, ent.getKey());
}
cxxSources.put(
ent.getKey(),
CxxSource.of(type.get(), ent.getValue().getSourcePath(), ent.getValue().getFlags()));
}
return cxxSources.build();
}
public static ImmutableList<StringWithMacrosArg> toStringWithMacrosArgs(
BuildTarget target,
CellPathResolver cellPathResolver,
BuildRuleResolver resolver,
CxxPlatform cxxPlatform,
Iterable<StringWithMacros> flags) {
ImmutableList.Builder<StringWithMacrosArg> args = ImmutableList.builder();
for (StringWithMacros flag : flags) {
args.add(
StringWithMacrosArg.of(
flag,
ImmutableList.of(new CxxLocationMacroExpander(cxxPlatform)),
target,
cellPathResolver,
resolver));
}
return args.build();
}
public static String normalizeModuleName(String moduleName) {
return moduleName.replaceAll("[^A-Za-z0-9]", "_");
}
}
| Use BuildRuleResolver.computeIfAbsentThrowing in CxxDescriptionEnhancer
Summary: Convert getRuleOptional + addToIndex to use the newly introduced BuildRuleResolver.computeIfAbsent.
Test Plan: CI
Reviewed By: dinhviethoa
fbshipit-source-id: 92075a4
| src/com/facebook/buck/cxx/CxxDescriptionEnhancer.java | Use BuildRuleResolver.computeIfAbsentThrowing in CxxDescriptionEnhancer | <ide><path>rc/com/facebook/buck/cxx/CxxDescriptionEnhancer.java
<ide> untypedTarget, headerVisibility, cxxPlatform.getFlavor());
<ide>
<ide> // Check the cache...
<del> Optional<BuildRule> rule = ruleResolver.getRuleOptional(headerSymlinkTreeTarget);
<del> if (rule.isPresent()) {
<del> Preconditions.checkState(rule.get() instanceof HeaderSymlinkTree);
<del> return (HeaderSymlinkTree) rule.get();
<del> }
<del>
<del> HeaderSymlinkTree symlinkTree =
<del> createHeaderSymlinkTree(
<del> untypedTarget,
<del> projectFilesystem,
<del> ruleResolver,
<del> cxxPlatform,
<del> headers,
<del> headerVisibility,
<del> shouldCreateHeadersSymlinks);
<del>
<del> ruleResolver.addToIndex(symlinkTree);
<del>
<del> return symlinkTree;
<add> return (HeaderSymlinkTree)
<add> ruleResolver.computeIfAbsent(
<add> headerSymlinkTreeTarget,
<add> () ->
<add> createHeaderSymlinkTree(
<add> untypedTarget,
<add> projectFilesystem,
<add> ruleResolver,
<add> cxxPlatform,
<add> headers,
<add> headerVisibility,
<add> shouldCreateHeadersSymlinks));
<ide> }
<ide>
<ide> private static SymlinkTree requireSandboxSymlinkTree(
<ide> ImmutableList.Builder<Arg> argsBuilder,
<ide> BuildTarget linkRuleTarget)
<ide> throws NoSuchBuildTargetException {
<del> CxxLink cxxLink;
<del> Optional<BuildRule> existingCxxLinkRule = resolver.getRuleOptional(linkRuleTarget);
<del> if (existingCxxLinkRule.isPresent()) {
<del> Preconditions.checkArgument(existingCxxLinkRule.get() instanceof CxxLink);
<del> cxxLink = (CxxLink) existingCxxLinkRule.get();
<del> } else {
<del> // Generate the final link rule. We use the top-level target as the link rule's
<del> // target, so that it corresponds to the actual binary we build.
<del> cxxLink =
<del> CxxLinkableEnhancer.createCxxLinkableBuildRule(
<del> cxxBuckConfig,
<del> cxxPlatform,
<del> params,
<del> resolver,
<del> sourcePathResolver,
<del> ruleFinder,
<del> linkRuleTarget,
<del> Linker.LinkType.EXECUTABLE,
<del> Optional.empty(),
<del> linkOutput,
<del> linkStyle,
<del> thinLto,
<del> deps,
<del> cxxRuntimeType,
<del> Optional.empty(),
<del> ImmutableSet.of(),
<del> NativeLinkableInput.builder()
<del> .setArgs(argsBuilder.build())
<del> .setFrameworks(frameworks)
<del> .setLibraries(libraries)
<del> .build(),
<del> Optional.empty());
<del> resolver.addToIndex(cxxLink);
<del> }
<del> return cxxLink;
<add> return (CxxLink)
<add> resolver.computeIfAbsentThrowing(
<add> linkRuleTarget,
<add> () ->
<add> // Generate the final link rule. We use the top-level target as the link rule's
<add> // target, so that it corresponds to the actual binary we build.
<add> CxxLinkableEnhancer.createCxxLinkableBuildRule(
<add> cxxBuckConfig,
<add> cxxPlatform,
<add> params,
<add> resolver,
<add> sourcePathResolver,
<add> ruleFinder,
<add> linkRuleTarget,
<add> Linker.LinkType.EXECUTABLE,
<add> Optional.empty(),
<add> linkOutput,
<add> linkStyle,
<add> thinLto,
<add> deps,
<add> cxxRuntimeType,
<add> Optional.empty(),
<add> ImmutableSet.of(),
<add> NativeLinkableInput.builder()
<add> .setArgs(argsBuilder.build())
<add> .setFrameworks(frameworks)
<add> .setLibraries(libraries)
<add> .build(),
<add> Optional.empty()));
<ide> }
<ide>
<ide> public static CxxStrip createCxxStripRule(
<ide> .withAppendedFlavors(CxxStrip.RULE_FLAVOR, stripStyle.getFlavor()))
<ide> .copyReplacingDeclaredAndExtraDeps(
<ide> ImmutableSortedSet.of(unstrippedBinaryRule), ImmutableSortedSet.of());
<del> Optional<BuildRule> exisitingRule = resolver.getRuleOptional(stripRuleParams.getBuildTarget());
<del> if (exisitingRule.isPresent()) {
<del> Preconditions.checkArgument(exisitingRule.get() instanceof CxxStrip);
<del> return (CxxStrip) exisitingRule.get();
<del> } else {
<del> CxxStrip cxxStrip =
<del> new CxxStrip(
<del> stripRuleParams,
<del> stripStyle,
<del> Preconditions.checkNotNull(unstrippedBinaryRule.getSourcePathToOutput()),
<del> cxxPlatform.getStrip(),
<del> CxxDescriptionEnhancer.getBinaryOutputPath(
<del> stripRuleParams.getBuildTarget(),
<del> params.getProjectFilesystem(),
<del> cxxPlatform.getBinaryExtension()));
<del> resolver.addToIndex(cxxStrip);
<del> return cxxStrip;
<del> }
<add> return (CxxStrip)
<add> resolver.computeIfAbsent(
<add> stripRuleParams.getBuildTarget(),
<add> () ->
<add> new CxxStrip(
<add> stripRuleParams,
<add> stripStyle,
<add> Preconditions.checkNotNull(unstrippedBinaryRule.getSourcePathToOutput()),
<add> cxxPlatform.getStrip(),
<add> CxxDescriptionEnhancer.getBinaryOutputPath(
<add> stripRuleParams.getBuildTarget(),
<add> params.getProjectFilesystem(),
<add> cxxPlatform.getBinaryExtension())));
<ide> }
<ide>
<ide> public static BuildRule createUberCompilationDatabase( |
|
Java | apache-2.0 | eaa5cd449a75239726a9c59b587aeabbfc4d6840 | 0 | eg-eng/Priam,giosg/Priam,scottmcmaster/Priam,Clearleap/Priam,Netflix/Priam,vinaykumarchella/Priam,vinaykumarchella/Priam,pqdev/Priam,muddman/Priam | package com.netflix.priam.defaultimpl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.priam.IConfiguration;
import com.netflix.priam.backup.Restore;
import com.netflix.priam.utils.CassandraTuner;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
public class StandardTuner implements CassandraTuner
{
private static final Logger logger = LoggerFactory.getLogger(StandardTuner.class);
protected final IConfiguration config;
@Inject
public StandardTuner(IConfiguration config)
{
this.config = config;
}
public void updateYaml(String yamlLocation, String hostname, String seedProvider) throws IOException
{
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
File yamlFile = new File(yamlLocation);
Map map = (Map) yaml.load(new FileInputStream(yamlFile));
map.put("cluster_name", config.getAppName());
map.put("storage_port", config.getStoragePort());
map.put("ssl_storage_port", config.getSSLStoragePort());
map.put("rpc_port", config.getThriftPort());
map.put("listen_address", hostname);
map.put("rpc_address", hostname);
//Dont bootstrap in restore mode
map.put("auto_bootstrap", !Restore.isRestoreEnabled(config));
map.put("saved_caches_directory", config.getCacheLocation());
map.put("commitlog_directory", config.getCommitLogLocation());
map.put("data_file_directories", Lists.newArrayList(config.getDataFileLocation()));
boolean enableIncremental = (config.getBackupHour() >= 0 && config.isIncrBackup()) && (CollectionUtils.isEmpty(config.getBackupRacs()) || config.getBackupRacs().contains(config.getRac()));
map.put("incremental_backups", enableIncremental);
map.put("endpoint_snitch", getSnitch());
map.put("in_memory_compaction_limit_in_mb", config.getInMemoryCompactionLimit());
map.put("compaction_throughput_mb_per_sec", config.getCompactionThroughput());
map.put("partitioner", derivePartitioner(map.get("partitioner").toString(), config.getPartitioner()));
map.put("memtable_total_space_in_mb", config.getMemtableTotalSpaceMB());
map.put("stream_throughput_outbound_megabits_per_sec", config.getStreamingThroughputMB());
map.put("multithreaded_compaction", config.getMultithreadedCompaction());
map.put("max_hint_window_in_ms", config.getMaxHintWindowInMS());
map.put("hinted_handoff_throttle_delay_in_ms", config.getHintHandoffDelay());
map.put("authenticator", config.getAuthenticator());
map.put("authorizer", config.getAuthorizer());
List<?> seedp = (List) map.get("seed_provider");
Map<String, String> m = (Map<String, String>) seedp.get(0);
m.put("class_name", seedProvider);
configureGlobalCaches(config, map);
map.put("num_tokens", config.getNumTokens());
logger.info(yaml.dump(map));
yaml.dump(map, new FileWriter(yamlFile));
}
/**
* Overridable by derived classes to inject a wrapper snitch.
*
* @return Sntich to be used by this cluster
*/
protected String getSnitch()
{
return config.getSnitch();
}
/**
* Setup the cassandra 1.1 global cache values
*/
private void configureGlobalCaches(IConfiguration config, Map yaml)
{
final String keyCacheSize = config.getKeyCacheSizeInMB();
if(keyCacheSize != null)
{
yaml.put("key_cache_size_in_mb", Integer.valueOf(keyCacheSize));
final String keyCount = config.getKeyCacheKeysToSave();
if(keyCount != null)
yaml.put("key_cache_keys_to_save", Integer.valueOf(keyCount));
}
final String rowCacheSize = config.getRowCacheSizeInMB();
if(rowCacheSize != null)
{
yaml.put("row_cache_size_in_mb", Integer.valueOf(rowCacheSize));
final String rowCount = config.getRowCacheKeysToSave();
if(rowCount != null)
yaml.put("row_cache_keys_to_save", Integer.valueOf(rowCount));
}
}
String derivePartitioner(String fromYaml, String fromConfig)
{
if(fromYaml == null || fromYaml.isEmpty())
return fromConfig;
//this check is to prevent against overwriting an existing yaml file that has
// a partitioner not RandomPartitioner or (as of cass 1.2) Murmur3Partitioner.
//basically we don't want to hose existing deployments by changing the partitioner unexpectedly on them
final String lowerCase = fromYaml.toLowerCase();
if(lowerCase.contains("randomparti") || lowerCase.contains("murmur"))
return fromConfig;
return fromYaml;
}
public void updateAutoBootstrap(String yamlFile, boolean autobootstrap) throws IOException
{
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
@SuppressWarnings("rawtypes")
Map map = (Map) yaml.load(new FileInputStream(yamlFile));
//Dont bootstrap in restore mode
map.put("auto_bootstrap", autobootstrap);
logger.info("Updating yaml" + yaml.dump(map));
yaml.dump(map, new FileWriter(yamlFile));
}
}
| priam/src/main/java/com/netflix/priam/defaultimpl/StandardTuner.java | package com.netflix.priam.defaultimpl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.priam.IConfiguration;
import com.netflix.priam.backup.Restore;
import com.netflix.priam.utils.CassandraTuner;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
public class StandardTuner implements CassandraTuner
{
private static final Logger logger = LoggerFactory.getLogger(StandardTuner.class);
protected final IConfiguration config;
@Inject
public StandardTuner(IConfiguration config)
{
this.config = config;
}
public void updateYaml(String yamlLocation, String hostname, String seedProvider) throws IOException
{
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
File yamlFile = new File(yamlLocation);
Map map = (Map) yaml.load(new FileInputStream(yamlFile));
map.put("cluster_name", config.getAppName());
map.put("storage_port", config.getStoragePort());
map.put("ssl_storage_port", config.getSSLStoragePort());
map.put("rpc_port", config.getThriftPort());
map.put("listen_address", hostname);
map.put("rpc_address", hostname);
//Dont bootstrap in restore mode
map.put("auto_bootstrap", !Restore.isRestoreEnabled(config));
map.put("saved_caches_directory", config.getCacheLocation());
map.put("commitlog_directory", config.getCommitLogLocation());
map.put("data_file_directories", Lists.newArrayList(config.getDataFileLocation()));
boolean enableIncremental = (config.getBackupHour() >= 0 && config.isIncrBackup()) && (CollectionUtils.isEmpty(config.getBackupRacs()) || config.getBackupRacs().contains(config.getRac()));
map.put("incremental_backups", enableIncremental);
map.put("endpoint_snitch", getSnitch());
map.put("in_memory_compaction_limit_in_mb", config.getInMemoryCompactionLimit());
map.put("compaction_throughput_mb_per_sec", config.getCompactionThroughput());
map.put("partitioner", derivePartitioner(map.get("partitioner").toString(), config.getPartitioner()));
map.put("memtable_total_space_in_mb", config.getMemtableTotalSpaceMB());
map.put("stream_throughput_outbound_megabits_per_sec", config.getStreamingThroughputMB());
map.put("multithreaded_compaction", config.getMultithreadedCompaction());
map.put("max_hint_window_in_ms", config.getMaxHintWindowInMS());
map.put("hinted_handoff_throttle_delay_in_ms", config.getHintHandoffDelay());
map.put("authenticator", config.getAuthenticator());
map.put("authority", config.getAuthorizer());
List<?> seedp = (List) map.get("seed_provider");
Map<String, String> m = (Map<String, String>) seedp.get(0);
m.put("class_name", seedProvider);
configureGlobalCaches(config, map);
map.put("num_tokens", config.getNumTokens());
logger.info(yaml.dump(map));
yaml.dump(map, new FileWriter(yamlFile));
}
/**
* Overridable by derived classes to inject a wrapper snitch.
*
* @return Sntich to be used by this cluster
*/
protected String getSnitch()
{
return config.getSnitch();
}
/**
* Setup the cassandra 1.1 global cache values
*/
private void configureGlobalCaches(IConfiguration config, Map yaml)
{
final String keyCacheSize = config.getKeyCacheSizeInMB();
if(keyCacheSize != null)
{
yaml.put("key_cache_size_in_mb", Integer.valueOf(keyCacheSize));
final String keyCount = config.getKeyCacheKeysToSave();
if(keyCount != null)
yaml.put("key_cache_keys_to_save", Integer.valueOf(keyCount));
}
final String rowCacheSize = config.getRowCacheSizeInMB();
if(rowCacheSize != null)
{
yaml.put("row_cache_size_in_mb", Integer.valueOf(rowCacheSize));
final String rowCount = config.getRowCacheKeysToSave();
if(rowCount != null)
yaml.put("row_cache_keys_to_save", Integer.valueOf(rowCount));
}
}
String derivePartitioner(String fromYaml, String fromConfig)
{
if(fromYaml == null || fromYaml.isEmpty())
return fromConfig;
//this check is to prevent against overwriting an existing yaml file that has
// a partitioner not RandomPartitioner or (as of cass 1.2) Murmur3Partitioner.
//basically we don't want to hose existing deployments by changing the partitioner unexpectedly on them
final String lowerCase = fromYaml.toLowerCase();
if(lowerCase.contains("randomparti") || lowerCase.contains("murmur"))
return fromConfig;
return fromYaml;
}
public void updateAutoBootstrap(String yamlFile, boolean autobootstrap) throws IOException
{
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
@SuppressWarnings("rawtypes")
Map map = (Map) yaml.load(new FileInputStream(yamlFile));
//Dont bootstrap in restore mode
map.put("auto_bootstrap", autobootstrap);
logger.info("Updating yaml" + yaml.dump(map));
yaml.dump(map, new FileWriter(yamlFile));
}
}
| backporting fix for writing auth values to yaml.
Also fixed the 1.1 yaml name 'authority' to 'authorizer' (changed in 1.2)
| priam/src/main/java/com/netflix/priam/defaultimpl/StandardTuner.java | backporting fix for writing auth values to yaml. Also fixed the 1.1 yaml name 'authority' to 'authorizer' (changed in 1.2) | <ide><path>riam/src/main/java/com/netflix/priam/defaultimpl/StandardTuner.java
<ide> map.put("max_hint_window_in_ms", config.getMaxHintWindowInMS());
<ide> map.put("hinted_handoff_throttle_delay_in_ms", config.getHintHandoffDelay());
<ide> map.put("authenticator", config.getAuthenticator());
<del> map.put("authority", config.getAuthorizer());
<add> map.put("authorizer", config.getAuthorizer());
<ide>
<ide> List<?> seedp = (List) map.get("seed_provider");
<ide> Map<String, String> m = (Map<String, String>) seedp.get(0); |
|
Java | epl-1.0 | 5efe613ac2e02f80626ef97e99242a2862c48a3c | 0 | ChangeOrientedProgrammingEnvironment/eclipseReplayer,ChangeOrientedProgrammingEnvironment/eclipseRecorder,ChangeOrientedProgrammingEnvironment/eclipseRecorder | package edu.oregonstate.cope.clientRecorder;
import java.util.regex.Pattern;
import org.json.simple.JSONObject;
import edu.oregonstate.cope.clientRecorder.fileOps.FileProvider;
/**
* Defines and implements JSON event persistence format. A FileManager must be
* set in order for the ChangePersister to function.
*
* <br>
* This class is a Singleton.
*/
public class ChangePersister {
private static final String SEPARATOR = "\n$@$";
public static final Pattern ELEMENT_REGEX = Pattern.compile(Pattern.quote(SEPARATOR) + "(\\{.*?\\})");
private FileProvider fileManager;
private static class Instance {
public static final ChangePersister instance = new ChangePersister();
}
private ChangePersister() {
}
// TODO This gets called on every persist. Maybe create a special
// FileProvider that knows how to initialize things on file swap
public void addInitEventIfAbsent() {
if (fileManager.isCurrentFileEmpty()) {
JSONObject markerObject = createInitJSON();
fileManager.appendToCurrentFile(ChangePersister.SEPARATOR);
fileManager.appendToCurrentFile(markerObject.toJSONString());
}
}
private JSONObject createInitJSON() {
JSONObject markerObject = new JSONObject();
markerObject.put("eventType", "FileInit");
return markerObject;
}
public static ChangePersister instance() {
return Instance.instance;
}
public void persist(JSONObject jsonObject) {
if (jsonObject == null) {
throw new RuntimeException("Argument cannot be null");
}
addInitEventIfAbsent();
fileManager.appendToCurrentFile(ChangePersister.SEPARATOR);
fileManager.appendToCurrentFile(jsonObject.toJSONString());
}
public void setFileManager(FileProvider fileManager) {
this.fileManager = fileManager;
addInitEventIfAbsent();
}
}
| edu.oregonstate.cope.clientrecorder/src/edu/oregonstate/cope/clientRecorder/ChangePersister.java | package edu.oregonstate.cope.clientRecorder;
import java.util.regex.Pattern;
import org.json.simple.JSONObject;
import edu.oregonstate.cope.clientRecorder.fileOps.FileProvider;
/**
* Persists JSON objects. This class is a Singleton. A FileManager must be set
* in order for the ChangePersister to function.
*/
public class ChangePersister {
private static final String SEPARATOR = "\n$@$";
public static final Pattern ELEMENT_REGEX = Pattern.compile(Pattern.quote(SEPARATOR) + "(\\{.*?\\})");
private FileProvider fileManager;
private static class Instance {
public static final ChangePersister instance = new ChangePersister();
}
private ChangePersister() {
}
public void init() {
if (fileManager.isCurrentFileEmpty()) {
JSONObject markerObject = createInitJSON();
fileManager.appendToCurrentFile(ChangePersister.SEPARATOR);
fileManager.appendToCurrentFile(markerObject.toJSONString());
}
}
private JSONObject createInitJSON() {
JSONObject markerObject = new JSONObject();
markerObject.put("eventType", "FileInit");
return markerObject;
}
public static ChangePersister instance() {
return Instance.instance;
}
public void persist(JSONObject jsonObject) {
if (jsonObject == null) {
throw new RuntimeException("Argument cannot be null");
}
init();
fileManager.appendToCurrentFile(ChangePersister.SEPARATOR);
fileManager.appendToCurrentFile(jsonObject.toJSONString());
}
public void setFileManager(FileProvider fileManager) {
this.fileManager = fileManager;
init();
}
}
| Code cleanup
Rename. Comments.
| edu.oregonstate.cope.clientrecorder/src/edu/oregonstate/cope/clientRecorder/ChangePersister.java | Code cleanup | <ide><path>du.oregonstate.cope.clientrecorder/src/edu/oregonstate/cope/clientRecorder/ChangePersister.java
<ide> import edu.oregonstate.cope.clientRecorder.fileOps.FileProvider;
<ide>
<ide> /**
<del> * Persists JSON objects. This class is a Singleton. A FileManager must be set
<del> * in order for the ChangePersister to function.
<add> * Defines and implements JSON event persistence format. A FileManager must be
<add> * set in order for the ChangePersister to function.
<add> *
<add> * <br>
<add> * This class is a Singleton.
<ide> */
<ide> public class ChangePersister {
<ide>
<ide> private ChangePersister() {
<ide> }
<ide>
<del> public void init() {
<add> // TODO This gets called on every persist. Maybe create a special
<add> // FileProvider that knows how to initialize things on file swap
<add> public void addInitEventIfAbsent() {
<ide> if (fileManager.isCurrentFileEmpty()) {
<ide> JSONObject markerObject = createInitJSON();
<ide>
<ide> if (jsonObject == null) {
<ide> throw new RuntimeException("Argument cannot be null");
<ide> }
<del>
<del> init();
<add>
<add> addInitEventIfAbsent();
<ide>
<ide> fileManager.appendToCurrentFile(ChangePersister.SEPARATOR);
<ide> fileManager.appendToCurrentFile(jsonObject.toJSONString());
<ide>
<ide> public void setFileManager(FileProvider fileManager) {
<ide> this.fileManager = fileManager;
<del> init();
<add> addInitEventIfAbsent();
<ide> }
<ide> } |
|
Java | lgpl-2.1 | 655489c543e98be1391ce5bb8a0fb63af1407d00 | 0 | julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine | package org.intermine.api.tracker;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.Queue;
import org.intermine.api.tracker.track.LoginTrack;
import org.intermine.api.tracker.track.Track;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.ObjectStoreWriterFactory;
import org.intermine.objectstore.intermine.ObjectStoreWriterInterMineImpl;
import junit.framework.TestCase;
public class TrackerLoggerTest extends TestCase {
ObjectStoreWriter uosw;
Connection con;
Queue<Track> trackQueue;
TrackerLogger trackerLogger = null;
private int count = 100;
protected void setUp() throws Exception {
super.setUp();
uosw = ObjectStoreWriterFactory.getObjectStoreWriter("osw.userprofile-test");
if (uosw instanceof ObjectStoreWriterInterMineImpl) {
con = ((ObjectStoreWriterInterMineImpl) uosw).getConnection();
}
trackQueue = new LinkedList<Track>();
//create the table if doesn't exist
LoginTracker.getInstance(con, trackQueue);
}
protected void tearDown() throws Exception {
super.tearDown();
removeTracks();
((ObjectStoreWriterInterMineImpl) uosw).releaseConnection(con);
}
public void testRun() throws SQLException, InterruptedException {
for (int index = 0; index < count; index++) {
trackQueue.add(new LoginTrack("user" + index,
new Timestamp(System.currentTimeMillis())));
}
trackerLogger = new TrackerLogger(con, trackQueue);
new Thread(trackerLogger).start();
synchronized (trackQueue) {
while (!trackQueue.isEmpty()) {
Thread.sleep(100);
}
}
String sql = "SELECT COUNT(*) FROM logintrack";
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery(sql);
rs.next();
assertEquals(count, rs.getInt(1));
rs.close();
stm.close();
}
private void removeTracks() throws SQLException {
String sql = "DELETE FROM logintrack";
Statement stm = con.createStatement();
stm.executeUpdate(sql);
stm.close();
}
}
| intermine/api/test/src/org/intermine/api/tracker/TrackerLoggerTest.java | package org.intermine.api.tracker;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.Queue;
import org.intermine.api.tracker.track.LoginTrack;
import org.intermine.api.tracker.track.Track;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.ObjectStoreWriterFactory;
import org.intermine.objectstore.intermine.ObjectStoreWriterInterMineImpl;
import junit.framework.TestCase;
public class TrackerLoggerTest extends TestCase {
ObjectStoreWriter uosw;
Connection con;
Queue<Track> trackQueue;
TrackerLogger trackerLogger = null;
protected void setUp() throws Exception {
super.setUp();
uosw = ObjectStoreWriterFactory.getObjectStoreWriter("osw.userprofile-test");
if (uosw instanceof ObjectStoreWriterInterMineImpl) {
con = ((ObjectStoreWriterInterMineImpl) uosw).getConnection();
}
trackQueue = new LinkedList<Track>();
//create the table if doesn't exist
LoginTracker.getInstance(con, trackQueue);
}
protected void tearDown() throws Exception {
super.tearDown();
removeTracks();
((ObjectStoreWriterInterMineImpl) uosw).releaseConnection(con);
}
public void testRun() throws SQLException, InterruptedException {
for (int index = 0; index < 100; index++) {
trackQueue.add(new LoginTrack("user" + index,
new Timestamp(System.currentTimeMillis())));
}
trackerLogger = new TrackerLogger(con, trackQueue);
new Thread(trackerLogger).start();
Thread.sleep(2000);
String sql = "SELECT COUNT(*) FROM logintrack";
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery(sql);
rs.next();
assertEquals(100, rs.getInt(1));
rs.close();
stm.close();
}
private void removeTracks() throws SQLException {
String sql = "DELETE FROM logintrack";
Statement stm = con.createStatement();
stm.executeUpdate(sql);
stm.close();
}
}
| Fixed thread synchronisation issue.
Former-commit-id: 4f1d01c543ce5c6838ca43a27da5db540e2313a2 | intermine/api/test/src/org/intermine/api/tracker/TrackerLoggerTest.java | Fixed thread synchronisation issue. | <ide><path>ntermine/api/test/src/org/intermine/api/tracker/TrackerLoggerTest.java
<ide> Connection con;
<ide> Queue<Track> trackQueue;
<ide> TrackerLogger trackerLogger = null;
<add> private int count = 100;
<ide>
<ide> protected void setUp() throws Exception {
<ide> super.setUp();
<ide> }
<ide>
<ide> public void testRun() throws SQLException, InterruptedException {
<del> for (int index = 0; index < 100; index++) {
<add> for (int index = 0; index < count; index++) {
<ide> trackQueue.add(new LoginTrack("user" + index,
<ide> new Timestamp(System.currentTimeMillis())));
<ide> }
<ide> trackerLogger = new TrackerLogger(con, trackQueue);
<ide> new Thread(trackerLogger).start();
<del> Thread.sleep(2000);
<add> synchronized (trackQueue) {
<add> while (!trackQueue.isEmpty()) {
<add> Thread.sleep(100);
<add> }
<add> }
<ide> String sql = "SELECT COUNT(*) FROM logintrack";
<ide> Statement stm = con.createStatement();
<ide> ResultSet rs = stm.executeQuery(sql);
<ide> rs.next();
<del> assertEquals(100, rs.getInt(1));
<add> assertEquals(count, rs.getInt(1));
<ide> rs.close();
<ide> stm.close();
<ide> } |
|
Java | apache-2.0 | 265e65b8f199d46f0c199b76b1eaf01c54ead43b | 0 | cosmocode/cosmocode-commons | /**
* Copyright 2010 CosmoCode GmbH
*
* 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 de.cosmocode.commons;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Calendar;
import java.util.Date;
/**
* Tests the public functions of overlap mode that are independent of the specific mode.
*
* @since 1.21
* @author Oliver Lorenz
*/
public final class OverlapModeGeneralTest {
private final OverlapMode mode = OverlapMode.NORMAL;
private Date yearFifty;
private Date yesterday;
private Date today;
private Date tomorrow;
private Date nextMonth;
@Before
public void setupPeriods() {
final Calendar calendar = Calendar.getInstance();
Calendars.toBeginningOfTheDay(calendar);
calendar.add(Calendar.DAY_OF_MONTH, -1);
yesterday = calendar.getTime();
calendar.add(Calendar.DAY_OF_MONTH, 1);
today = calendar.getTime();
calendar.add(Calendar.DAY_OF_MONTH, 1);
tomorrow = calendar.getTime();
calendar.add(Calendar.MONTH, 1);
nextMonth = calendar.getTime();
// special
calendar.set(Calendar.YEAR, 50);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
yearFifty = calendar.getTime();
}
@Test
public void timePeriodsOverlap() {
final TimePeriod a = Dates.timePeriod(today, tomorrow);
final TimePeriod b = Dates.timePeriod(today, nextMonth);
final boolean expected = true;
final boolean actual = mode.isOverlapping(a, b);
Assert.assertEquals(expected, actual);
}
@Test
public void timePeriodsOverlapImmutableDateAndDayPrecision() {
final TimePeriod a = Dates.timePeriod(yesterday, tomorrow);
final TimePeriod b = new DayPrecisionTimePeriod(today, nextMonth);
final boolean expected = true;
final boolean actual = mode.isOverlapping(a, b);
Assert.assertEquals(expected, actual);
}
@Test
public void timePeriodsNotOverlappingImmutableDateAndDayPrecision() {
final TimePeriod a = Dates.timePeriod(yesterday, today);
final TimePeriod b = new DayPrecisionTimePeriod(tomorrow, nextMonth);
final boolean expected = false;
final boolean actual = mode.isOverlapping(a, b);
Assert.assertEquals(expected, actual);
}
@Test
public void timePeriodsOverlapDayPrecisionAndImmutableDate() {
final TimePeriod a = new DayPrecisionTimePeriod(today, nextMonth);
final TimePeriod b = Dates.timePeriod(yesterday, tomorrow);
final boolean expected = true;
final boolean actual = mode.isOverlapping(a, b);
Assert.assertEquals(expected, actual);
}
@Test
public void timePeriodsOverlapYearFive() {
// first period: year 2 to year 200
final TimePeriod a = new DayPrecisionTimePeriod(2L * 365L, 200L * 365L);
final TimePeriod b = Dates.timePeriod(yearFifty, today);
final boolean expected = true;
final boolean actual = mode.isOverlapping(a, b);
Assert.assertEquals(expected, actual);
}
@Test
public void timePeriodsOverlapYearFiveReversed() {
// first period: year 2 to year 200
final TimePeriod a = Dates.timePeriod(yearFifty, today);
final TimePeriod b = new DayPrecisionTimePeriod(2L * 365L, 200L * 365L);
final boolean expected = true;
final boolean actual = mode.isOverlapping(a, b);
Assert.assertEquals(expected, actual);
}
}
| src/test/java/de/cosmocode/commons/OverlapModeGeneralTest.java | /**
* Copyright 2010 CosmoCode GmbH
*
* 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 de.cosmocode.commons;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Calendar;
import java.util.Date;
/**
* Tests the public functions of overlap mode that are independent of the specific mode.
*
* @since 1.21
* @author Oliver Lorenz
*/
public final class OverlapModeGeneralTest {
private final OverlapMode mode = OverlapMode.NORMAL;
private Date yearFifty;
private Date yesterday;
private Date today;
private Date tomorrow;
private Date nextMonth;
@Before
public void setupPeriods() {
final Calendar calendar = Calendar.getInstance();
Calendars.toBeginningOfTheDay(calendar);
calendar.add(Calendar.DAY_OF_MONTH, -1);
yesterday = calendar.getTime();
calendar.add(Calendar.DAY_OF_MONTH, 1);
today = calendar.getTime();
calendar.add(Calendar.DAY_OF_MONTH, 1);
tomorrow = calendar.getTime();
calendar.add(Calendar.MONTH, 1);
nextMonth = calendar.getTime();
// special
calendar.set(Calendar.YEAR, 50);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
yearFifty = calendar.getTime();
}
@Test
public void timePeriodsOverlap() {
final TimePeriod a = Dates.timePeriod(today, tomorrow);
final TimePeriod b = Dates.timePeriod(today, nextMonth);
final boolean expected = true;
final boolean actual = mode.isOverlapping(a, b);
Assert.assertEquals(expected, actual);
}
@Test
public void timePeriodsOverlapImmutableDateAndDayPrecision() {
final TimePeriod a = Dates.timePeriod(yesterday, tomorrow);
final TimePeriod b = new DayPrecisionTimePeriod(today, nextMonth);
final boolean expected = true;
final boolean actual = mode.isOverlapping(a, b);
Assert.assertEquals(expected, actual);
}
@Test
public void timePeriodsNotOverlappingImmutableDateAndDayPrecision() {
final TimePeriod a = Dates.timePeriod(yesterday, today);
final TimePeriod b = new DayPrecisionTimePeriod(tomorrow, nextMonth);
final boolean expected = false;
final boolean actual = mode.isOverlapping(a, b);
Assert.assertEquals(expected, actual);
}
@Test
public void timePeriodsOverlapDayPrecisionAndImmutableDate() {
final TimePeriod a = new DayPrecisionTimePeriod(today, nextMonth);
final TimePeriod b = Dates.timePeriod(yesterday, tomorrow);
final boolean expected = true;
final boolean actual = mode.isOverlapping(a, b);
Assert.assertEquals(expected, actual);
}
@Test
public void timePeriodsOverlapYearFive() {
// first period: year 2 to year 200
final TimePeriod a = new DayPrecisionTimePeriod(2L * 365L, 200L * 365L);
final TimePeriod b = Dates.timePeriod(yearFifty, today);
final boolean expexted = true;
final boolean actual = mode.isOverlapping(a, b);
Assert.assertEquals(expexted, actual);
}
}
| added reverse test, fixed typo
| src/test/java/de/cosmocode/commons/OverlapModeGeneralTest.java | added reverse test, fixed typo | <ide><path>rc/test/java/de/cosmocode/commons/OverlapModeGeneralTest.java
<ide> final TimePeriod a = new DayPrecisionTimePeriod(2L * 365L, 200L * 365L);
<ide> final TimePeriod b = Dates.timePeriod(yearFifty, today);
<ide>
<del> final boolean expexted = true;
<add> final boolean expected = true;
<ide> final boolean actual = mode.isOverlapping(a, b);
<del> Assert.assertEquals(expexted, actual);
<add> Assert.assertEquals(expected, actual);
<add> }
<add>
<add> @Test
<add> public void timePeriodsOverlapYearFiveReversed() {
<add> // first period: year 2 to year 200
<add> final TimePeriod a = Dates.timePeriod(yearFifty, today);
<add> final TimePeriod b = new DayPrecisionTimePeriod(2L * 365L, 200L * 365L);
<add>
<add> final boolean expected = true;
<add> final boolean actual = mode.isOverlapping(a, b);
<add> Assert.assertEquals(expected, actual);
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | d8f0ca3bdf783b00ea7360eed51bd49f5e8a7f8b | 0 | abhinavmishra14/sigar,kaustavha/sigar,scouter-project/sigar,ruleless/sigar,monicasarbu/sigar,ruleless/sigar,scouter-project/sigar,kaustavha/sigar,cit-lab/sigar,cit-lab/sigar,abhinavmishra14/sigar,lsjeng/sigar,lsjeng/sigar,ChunPIG/sigar,racker/sigar,boundary/sigar,hyperic/sigar,abhinavmishra14/sigar,monicasarbu/sigar,ruleless/sigar,cit-lab/sigar,formicary/sigar,formicary/sigar,OlegYch/sigar,hyperic/sigar,abhinavmishra14/sigar,OlegYch/sigar,racker/sigar,abhinavmishra14/sigar,lsjeng/sigar,hyperic/sigar,cit-lab/sigar,hyperic/sigar,scouter-project/sigar,OlegYch/sigar,scouter-project/sigar,ChunPIG/sigar,OlegYch/sigar,monicasarbu/sigar,ruleless/sigar,boundary/sigar,racker/sigar,OlegYch/sigar,formicary/sigar,monicasarbu/sigar,monicasarbu/sigar,ChunPIG/sigar,OlegYch/sigar,racker/sigar,formicary/sigar,monicasarbu/sigar,scouter-project/sigar,monicasarbu/sigar,lsjeng/sigar,formicary/sigar,scouter-project/sigar,scouter-project/sigar,ChunPIG/sigar,scouter-project/sigar,OlegYch/sigar,kaustavha/sigar,kaustavha/sigar,ChunPIG/sigar,cit-lab/sigar,ruleless/sigar,cit-lab/sigar,racker/sigar,monicasarbu/sigar,boundary/sigar,scouter-project/sigar,kaustavha/sigar,abhinavmishra14/sigar,boundary/sigar,kaustavha/sigar,couchbase/sigar,boundary/sigar,OlegYch/sigar,ruleless/sigar,ChunPIG/sigar,cit-lab/sigar,hyperic/sigar,hyperic/sigar,ChunPIG/sigar,racker/sigar,ruleless/sigar,formicary/sigar,hyperic/sigar,abhinavmishra14/sigar,lsjeng/sigar,lsjeng/sigar,ChunPIG/sigar,boundary/sigar,hyperic/sigar,formicary/sigar,formicary/sigar,kaustavha/sigar,cit-lab/sigar,ruleless/sigar,OlegYch/sigar,OlegYch/sigar,ruleless/sigar,boundary/sigar,racker/sigar,formicary/sigar,racker/sigar,scouter-project/sigar,lsjeng/sigar,boundary/sigar,lsjeng/sigar,kaustavha/sigar,monicasarbu/sigar,hyperic/sigar,cit-lab/sigar,hyperic/sigar,ruleless/sigar,racker/sigar,ChunPIG/sigar,cit-lab/sigar,abhinavmishra14/sigar,hyperic/sigar,kaustavha/sigar,scouter-project/sigar,monicasarbu/sigar,boundary/sigar,kaustavha/sigar,ChunPIG/sigar,abhinavmishra14/sigar,cit-lab/sigar,monicasarbu/sigar,lsjeng/sigar,abhinavmishra14/sigar,racker/sigar,formicary/sigar,kaustavha/sigar,abhinavmishra14/sigar,couchbase/sigar,boundary/sigar,lsjeng/sigar | package net.hyperic.sigar;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.util.Properties;
import java.util.StringTokenizer;
public class OperatingSystem {
private static final String ETC =
System.getProperty("sigar.etc.dir", "/etc") + "/";
private static OperatingSystem instance = null;
private String name;
private String version;
private String arch;
private String patchLevel;
private String vendor;
private String vendorVersion;
private OperatingSystem() {
}
public static synchronized OperatingSystem getInstance() {
if (instance == null) {
OperatingSystem os = new OperatingSystem();
Properties props = System.getProperties();
os.name = props.getProperty("os.name");
os.version = props.getProperty("os.version");
os.arch = props.getProperty("os.arch");
os.patchLevel = props.getProperty("sun.os.patch.level");
if (os.name.equals("Linux")) {
os.getLinuxInfo();
}
instance = os;
}
return instance;
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
public String getArch() {
return this.arch;
}
public String getPatchLevel() {
return this.patchLevel;
}
public String getVendor() {
return this.vendor;
}
public String getVendorVersion() {
return this.vendorVersion;
}
private void getLinuxInfo() {
VendorInfo[] info = {
new GenericVendor("mandrake-release", "Mandrake"),
new GenericVendor("SuSE-release", "SuSE"),
new GenericVendor("gentoo-release", "Gentoo"),
new GenericVendor("debian_version", "Debian"),
new GenericVendor("slackware-version", "Slackware"),
new GenericVendor("fedora-release", "Fedora"),
new RedHatVendor("redhat-release", "Red Hat"),
};
for (int i=0; i<info.length; i++) {
File file = new File(info[i].getFileName());
if (!file.exists()) {
continue;
}
FileReader reader = null;
try {
int len = (int)file.length();
char[] data = new char[len];
reader = new FileReader(file);
reader.read(data, 0, len);
info[i].parse(new String(data), this);
} catch (IOException e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) { }
}
}
break;
}
}
private static String parseVersion(String line) {
StringTokenizer tok = new StringTokenizer(line);
while (tok.hasMoreTokens()) {
String s = tok.nextToken();
if (Character.isDigit(s.charAt(0))) {
int i;
for (i=1; i<s.length(); i++) {
char c = s.charAt(i);
if (!(Character.isDigit(c) || (c == '.'))) {
break;
}
}
return s.substring(0, i);
}
}
return null;
}
private interface VendorInfo {
public String getFileName();
public void parse(String data, OperatingSystem os);
}
private class RedHatVendor extends GenericVendor {
public RedHatVendor(String file, String name) {
super(file, name);
}
public void parse(String line, OperatingSystem os) {
super.parse(line, os);
String token = "Red Hat Enterprise Linux AS";
if (line.startsWith(token)) {
os.vendorVersion = "AS " + os.vendorVersion;
}
}
}
private class GenericVendor implements VendorInfo {
private String file;
private String name;
public GenericVendor(String file, String name) {
this.file = file;
this.name = name;
}
public String getFileName() {
return ETC + this.file;
}
public void parse(String line, OperatingSystem os) {
os.vendor = this.name;
os.vendorVersion = parseVersion(line);
}
}
public static void main(String[] args) {
OperatingSystem os = OperatingSystem.getInstance();
System.out.println("vendor..." + os.vendor);
System.out.println("vendor version..." + os.vendorVersion);
}
}
| bindings/java/src/net/hyperic/sigar/OperatingSystem.java | package net.hyperic.sigar;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.util.Properties;
import java.util.StringTokenizer;
public class OperatingSystem {
private static final String ETC =
System.getProperty("sigar.etc.dir", "/etc") + "/";
private String name;
private String version;
private String arch;
private String patchLevel;
private String vendor;
private String vendorVersion;
private OperatingSystem() {
}
public static OperatingSystem getInstance() {
OperatingSystem os = new OperatingSystem();
Properties props = System.getProperties();
os.name = props.getProperty("os.name");
os.version = props.getProperty("os.version");
os.arch = props.getProperty("os.arch");
os.patchLevel = props.getProperty("sun.os.patch.level");
if (os.name.equals("Linux")) {
os.getLinuxInfo();
}
return os;
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
public String getArch() {
return this.arch;
}
public String getPatchLevel() {
return this.patchLevel;
}
public String getVendor() {
return this.vendor;
}
public String getVendorVersion() {
return this.vendorVersion;
}
private void getLinuxInfo() {
VendorInfo[] info = {
new GenericVendor("mandrake-release", "Mandrake"),
new GenericVendor("SuSE-release", "SuSE"),
new GenericVendor("gentoo-release", "Gentoo"),
new GenericVendor("debian_version", "Debian"),
new GenericVendor("slackware-version", "Slackware"),
new GenericVendor("fedora-release", "Fedora"),
new RedHatVendor("redhat-release", "Red Hat"),
};
for (int i=0; i<info.length; i++) {
File file = new File(info[i].getFileName());
if (!file.exists()) {
continue;
}
FileReader reader = null;
try {
int len = (int)file.length();
char[] data = new char[len];
reader = new FileReader(file);
reader.read(data, 0, len);
info[i].parse(new String(data), this);
} catch (IOException e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) { }
}
}
break;
}
}
private static String parseVersion(String line) {
StringTokenizer tok = new StringTokenizer(line);
while (tok.hasMoreTokens()) {
String s = tok.nextToken();
if (Character.isDigit(s.charAt(0))) {
int i;
for (i=1; i<s.length(); i++) {
char c = s.charAt(i);
if (!(Character.isDigit(c) || (c == '.'))) {
break;
}
}
return s.substring(0, i);
}
}
return null;
}
private interface VendorInfo {
public String getFileName();
public void parse(String data, OperatingSystem os);
}
private class RedHatVendor extends GenericVendor {
public RedHatVendor(String file, String name) {
super(file, name);
}
public void parse(String line, OperatingSystem os) {
super.parse(line, os);
String token = "Red Hat Enterprise Linux AS";
if (line.startsWith(token)) {
os.vendorVersion = "AS " + os.vendorVersion;
}
}
}
private class GenericVendor implements VendorInfo {
private String file;
private String name;
public GenericVendor(String file, String name) {
this.file = file;
this.name = name;
}
public String getFileName() {
return ETC + this.file;
}
public void parse(String line, OperatingSystem os) {
os.vendor = this.name;
os.vendorVersion = parseVersion(line);
}
}
public static void main(String[] args) {
OperatingSystem os = OperatingSystem.getInstance();
System.out.println("vendor..." + os.vendor);
System.out.println("vendor version..." + os.vendorVersion);
}
}
| only create one instance
| bindings/java/src/net/hyperic/sigar/OperatingSystem.java | only create one instance | <ide><path>indings/java/src/net/hyperic/sigar/OperatingSystem.java
<ide> private static final String ETC =
<ide> System.getProperty("sigar.etc.dir", "/etc") + "/";
<ide>
<add> private static OperatingSystem instance = null;
<add>
<ide> private String name;
<ide> private String version;
<ide> private String arch;
<ide> private OperatingSystem() {
<ide> }
<ide>
<del> public static OperatingSystem getInstance() {
<del> OperatingSystem os = new OperatingSystem();
<del> Properties props = System.getProperties();
<del> os.name = props.getProperty("os.name");
<del> os.version = props.getProperty("os.version");
<del> os.arch = props.getProperty("os.arch");
<del> os.patchLevel = props.getProperty("sun.os.patch.level");
<add> public static synchronized OperatingSystem getInstance() {
<add> if (instance == null) {
<add> OperatingSystem os = new OperatingSystem();
<add> Properties props = System.getProperties();
<add> os.name = props.getProperty("os.name");
<add> os.version = props.getProperty("os.version");
<add> os.arch = props.getProperty("os.arch");
<add> os.patchLevel = props.getProperty("sun.os.patch.level");
<ide>
<del> if (os.name.equals("Linux")) {
<del> os.getLinuxInfo();
<add> if (os.name.equals("Linux")) {
<add> os.getLinuxInfo();
<add> }
<add>
<add> instance = os;
<ide> }
<ide>
<del> return os;
<add> return instance;
<ide> }
<ide>
<ide> public String getName() { |
|
Java | mit | 3605b85acaa8468b2c22aa793bd73a8268b69f7d | 0 | tobsinger/dreamy | package de.dreamy;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.service.dreams.DreamService;
import android.service.notification.StatusBarNotification;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import de.dreamy.notifications.NotificationListener;
import de.dreamy.settings.Settings;
import de.dreamy.settings.SettingsDao;
import de.dreamy.view.TimelyClock;
import de.dreamy.view.adapters.NotificationListAdapter;
/**
* The actual day dream service implementation
*/
public class DreamyDaydream extends DreamService implements AdapterView.OnItemClickListener, View.OnClickListener {
private final String TAG = DreamyDaydream.class.getCanonicalName();
@Inject
SettingsDao settingsDao;
/**
* The list that holds the notification views
*/
private ListView listView;
/**
* The animated clock
*/
private TimelyClock timelyClock;
/**
* The field to display the current battery level
*/
private TextView batteryPercentage;
/**
* The battery icon
*/
private ImageView batteryIcon;
private LocalBroadcastManager localBroadcastManager;
/**
* Broadcast receiver to handle incoming notifications
*/
private BroadcastReceiver notificationBroadcastReceiver = new BroadcastReceiver() {
/**
* {@inheritDoc}
*/
@Override
public void onReceive(Context context, Intent intent) {
displayNotifications();
}
};
/**
* Broadcast receiver to handle battery state change events
*/
private BroadcastReceiver batteryBroadcastReceiver = new BroadcastReceiver() {
/**
* {@inheritDoc}
*/
@Override
public void onReceive(Context context, Intent batteryStatus) {
// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int batteryPct = (int) (level / (float) scale * 100);
if (batteryIcon != null) {
batteryIcon.setVisibility(View.VISIBLE);
if (isCharging) {
batteryIcon.setImageResource(R.drawable.ic_battery_charging_full_white_48dp);
} else {
batteryIcon.setImageResource(R.drawable.ic_battery_full_white_48dp);
}
}
if (batteryPercentage != null) {
batteryPercentage.setText(batteryPct + "%");
}
}
};
/**
* {@inheritDoc}
*/
@Override
public void onCreate() {
super.onCreate();
DreamyApplication.getDreamyComponent().inject(this);
Log.d(TAG, "creating daydream service");
initBroadcastManager();
}
/**
* {@inheritDoc}
*/
@Override
public void onAttachedToWindow() {
//setup daydream
super.onAttachedToWindow();
final Settings settings = settingsDao.getSettings(this);
// Change Screen brightness
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = settings.getScreenBrightness();
getWindow().setAttributes(layout);
setInteractive(true);
setFullscreen(true);
final Point screenSize = new Point();
getWindowManager().getDefaultDisplay().getSize(screenSize);
setContentView(R.layout.daydream_layout);
final NotificationListAdapter adapter = new NotificationListAdapter(this);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
listView.setAlpha(settings.getNotificationVisibility());
timelyClock = (TimelyClock) findViewById(R.id.timelyClock);
timelyClock.setOnClickListener(this);
batteryPercentage = (TextView) findViewById(R.id.batteryPercentage);
batteryIcon = (ImageView) findViewById(R.id.batteryIcon);
if (settings.isShowBatteryStatus()) {
findViewById(R.id.batteryInfo).setVisibility(View.VISIBLE);
}
if (settings.isShowWifiStatus()) {
final View wifiInfo = findViewById(R.id.wifiInfo);
final String currentWifi = getCurrentWifi();
if (currentWifi != null) {
wifiInfo.setVisibility(View.VISIBLE);
final TextView wifiName = (TextView) findViewById(R.id.wifiName);
wifiName.setText(currentWifi);
} else {
wifiInfo.setVisibility(View.GONE);
}
}
if (settings.isShowCarrierName()) {
final TextView carrierTextView = (TextView) findViewById(R.id.carrierName);
carrierTextView.setVisibility(View.VISIBLE);
carrierTextView.setText(getCarrierName());
}
if (settings.isShowBatteryStatus()) {
updateBatteryLevel();
}
// Debug.waitForDebugger();
}
/**
* {@inheritDoc}
*/
@Override
public void onClick(View v) {
if (timelyClock.equals(v) && settingsDao.getSettings(this).isWakeOnTimeClick()) {
this.finish();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onDreamingStarted() {
super.onDreamingStarted();
if (settingsDao.getSettings(this).isShowNotifications()) {
displayNotifications();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onDetachedFromWindow() {
this.unregisterReceiver(batteryBroadcastReceiver);
localBroadcastManager.unregisterReceiver(notificationBroadcastReceiver);
super.onDetachedFromWindow();
}
/**
* {@inheritDoc}
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final StatusBarNotification notification = (StatusBarNotification) parent.getAdapter().getItem(position);
try {
notification.getNotification().contentIntent.send();
this.finish();
} catch (PendingIntent.CanceledException e) {
Log.d(TAG, "intent canceled");
}
}
/**
* Initiate the broadcast manager and register the receiver for notifications about
* new status bar notifications
*/
private void initBroadcastManager() {
final Settings settings = settingsDao.getSettings(this);
if (settings.isShowNotifications()) {
localBroadcastManager = LocalBroadcastManager.getInstance(this);
final IntentFilter filter = new IntentFilter();
filter.addAction(Constants.INTENT_FILTER_NOTIFICATION_UPDATE);
localBroadcastManager.registerReceiver(notificationBroadcastReceiver, filter);
}
if (settings.isShowBatteryStatus()) {
final IntentFilter batteryStatusIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
this.registerReceiver(batteryBroadcastReceiver, batteryStatusIntentFilter);
}
}
/**
* Get the current list of status bar notifications, remove duplicates and display the rest in the list view
*/
private void displayNotifications() {
final List<StatusBarNotification> allNotifications = NotificationListener.getNotifications();
final List<StatusBarNotification> filteredNotifications = new ArrayList<>();
final List<Integer> notifications = new ArrayList<>();
for (final StatusBarNotification n : allNotifications) {
int singleNotificationIdentifier = getNotificationIdentifier(n.getNotification());
if (!notifications.contains(singleNotificationIdentifier)
&& ((isOnlyNotificationWithGroupKey(n, allNotifications))
|| (n.getNotification().visibility == Notification.VISIBILITY_PUBLIC
|| n.getNotification().publicVersion != null))) {
filteredNotifications.add(n);
notifications.add(singleNotificationIdentifier);
}
}
if (listView != null) {
((NotificationListAdapter) listView.getAdapter()).setNotifications(new ArrayList<>(filteredNotifications));
}
}
/**
* Check if there isn't a public notification with the same group key
*
* @param notification The notification to find a public version for
* @param allNotifications The list of all notifications
* @return True if there is no public version of the notification
*/
private boolean isOnlyNotificationWithGroupKey(final StatusBarNotification notification, final List<StatusBarNotification> allNotifications) {
if (TextUtils.isEmpty(notification.getGroupKey())) {
return true;
}
for (final StatusBarNotification singleNotification : allNotifications) {
if (!notification.equals(singleNotification) && notification.getGroupKey().equals(singleNotification.getGroupKey())) {
if ((singleNotification.getNotification().visibility == Notification.VISIBILITY_PUBLIC || singleNotification.getNotification().publicVersion != null)) {
return false;
}
}
}
return true;
}
/**
* Get an identifier for the notification based on the notifications content
*
* @param notification The notification to generate an identifier for
* @return The generated identifier
*/
private int getNotificationIdentifier(final Notification notification) {
final Date date = new Date(notification.when);
final String dateString = new SimpleDateFormat(Constants.TIME_PATTERN, Locale.GERMANY).format(date);
final Bundle extras = notification.extras;
final ApplicationInfo applicationInfo = ((ApplicationInfo) extras.get(Constants.NOTIFICATION_APP));
final String identifierString = "" + dateString + (applicationInfo != null ? applicationInfo.className : "") + extras.get(Constants.NOTIFICATION_TITLE) + extras.get(Constants.NOTIFICATION_CONTENT);
return identifierString.hashCode();
}
/**
* Get the name of the currently connected wifi
*
* @return the name of the currently connected wifi. NULL if no wifi connected
*/
private String getCurrentWifi() {
final ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final Network networks[] = connManager.getAllNetworks();
for (final Network singleNetwork : networks) {
final NetworkInfo networkInfo = connManager.getNetworkInfo(singleNetwork);
if (ConnectivityManager.TYPE_WIFI == networkInfo.getType()) {
if (!networkInfo.isConnected()) {
continue;
}
if (networkInfo.isConnected()) {
final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null) {
String ssid = connectionInfo.getSSID();
String quotes = String.valueOf('"');
if (ssid.startsWith(quotes)) {
ssid = ssid.substring(1, ssid.length());
}
if (ssid.endsWith(quotes)) {
ssid = ssid.substring(0, ssid.length() - 1);
}
return ssid;
}
}
}
}
return null;
}
/**
* Get the name of the current carrier
*
* @return A string with the carrier's name
*/
private String getCarrierName() {
final TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
final String carrierName = manager.getNetworkOperatorName();
return carrierName;
}
/**
* Get the current battery level and send it to the receiver
*
* @return
*/
public void updateBatteryLevel() {
final Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
batteryBroadcastReceiver.onReceive(this, batteryIntent);
}
}
| app/src/main/java/de/dreamy/DreamyDaydream.java | package de.dreamy;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.service.dreams.DreamService;
import android.service.notification.StatusBarNotification;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import de.dreamy.notifications.NotificationListener;
import de.dreamy.settings.Settings;
import de.dreamy.settings.SettingsDao;
import de.dreamy.view.TimelyClock;
import de.dreamy.view.adapters.NotificationListAdapter;
/**
* The actual day dream service implementation
*/
public class DreamyDaydream extends DreamService implements AdapterView.OnItemClickListener, View.OnClickListener {
private final String TAG = DreamyDaydream.class.getCanonicalName();
@Inject
SettingsDao settingsDao;
/**
* The list that holds the notification views
*/
private ListView listView;
/**
* The animated clock
*/
private TimelyClock timelyClock;
/**
* The field to display the current battery level
*/
private TextView batteryPercentage;
/**
* The battery icon
*/
private ImageView batteryIcon;
private LocalBroadcastManager localBroadcastManager;
/**
* Broadcast receiver to handle incoming notifications
*/
private BroadcastReceiver notificationBroadcastReceiver = new BroadcastReceiver() {
/**
* {@inheritDoc}
*/
@Override
public void onReceive(Context context, Intent intent) {
displayNotifications();
}
};
/**
* Broadcast receiver to handle battery state change events
*/
private BroadcastReceiver batteryBroadcastReceiver = new BroadcastReceiver() {
/**
* {@inheritDoc}
*/
@Override
public void onReceive(Context context, Intent batteryStatus) {
// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int batteryPct = (int) (level / (float) scale * 100);
if (batteryIcon != null) {
batteryIcon.setVisibility(View.VISIBLE);
if (isCharging) {
batteryIcon.setImageResource(R.drawable.ic_battery_charging_full_white_48dp);
} else {
batteryIcon.setImageResource(R.drawable.ic_battery_full_white_48dp);
}
}
if (batteryPercentage != null) {
batteryPercentage.setText(batteryPct + "%");
}
}
};
/**
* {@inheritDoc}
*/
@Override
public void onCreate() {
super.onCreate();
DreamyApplication.getDreamyComponent().inject(this);
Log.d(TAG, "creating daydream service");
initBroadcastManager();
}
/**
* {@inheritDoc}
*/
@Override
public void onAttachedToWindow() {
//setup daydream
super.onAttachedToWindow();
final Settings settings = settingsDao.getSettings(this);
// Change Screen brightness
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = settings.getScreenBrightness();
getWindow().setAttributes(layout);
setInteractive(true);
setFullscreen(true);
final Point screenSize = new Point();
getWindowManager().getDefaultDisplay().getSize(screenSize);
setContentView(R.layout.daydream_layout);
final NotificationListAdapter adapter = new NotificationListAdapter(this);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
listView.setAlpha(settings.getNotificationVisibility());
timelyClock = (TimelyClock) findViewById(R.id.timelyClock);
timelyClock.setOnClickListener(this);
batteryPercentage = (TextView) findViewById(R.id.batteryPercentage);
batteryIcon = (ImageView) findViewById(R.id.batteryIcon);
if (settings.isShowBatteryStatus()) {
findViewById(R.id.batteryInfo).setVisibility(View.VISIBLE);
}
if (settings.isShowWifiStatus()) {
final View wifiInfo = findViewById(R.id.wifiInfo);
final String currentWifi = getCurrentWifi();
if (currentWifi != null) {
wifiInfo.setVisibility(View.VISIBLE);
final TextView wifiName = (TextView) findViewById(R.id.wifiName);
wifiName.setText(currentWifi);
} else {
wifiInfo.setVisibility(View.GONE);
}
}
if (settings.isShowCarrierName()) {
final TextView carrierTextView = (TextView) findViewById(R.id.carrierName);
carrierTextView.setVisibility(View.VISIBLE);
carrierTextView.setText(getCarrierName());
}
// Debug.waitForDebugger();
}
/**
* {@inheritDoc}
*/
@Override
public void onClick(View v) {
if (timelyClock.equals(v) && settingsDao.getSettings(this).isWakeOnTimeClick()) {
this.finish();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onDreamingStarted() {
super.onDreamingStarted();
if (settingsDao.getSettings(this).isShowNotifications()) {
displayNotifications();
}
}
@Override
public void onDetachedFromWindow() {
this.unregisterReceiver(batteryBroadcastReceiver);
localBroadcastManager.unregisterReceiver(notificationBroadcastReceiver);
super.onDetachedFromWindow();
}
/**
* {@inheritDoc}
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final StatusBarNotification notification = (StatusBarNotification) parent.getAdapter().getItem(position);
try {
notification.getNotification().contentIntent.send();
this.finish();
} catch (PendingIntent.CanceledException e) {
Log.d(TAG, "intent canceled");
}
}
/**
* Initiate the broadcast manager and register the receiver for notifications about
* new status bar notifications
*/
private void initBroadcastManager() {
localBroadcastManager = LocalBroadcastManager.getInstance(this);
final IntentFilter filter = new IntentFilter();
filter.addAction(Constants.INTENT_FILTER_NOTIFICATION_UPDATE);
localBroadcastManager.registerReceiver(notificationBroadcastReceiver, filter);
if (settingsDao.getSettings(this).isShowBatteryStatus()) {
final IntentFilter batteryStatusIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
this.registerReceiver(batteryBroadcastReceiver, batteryStatusIntentFilter);
}
}
/**
* Get the current list of status bar notifications, remove duplicates and display the rest in the list view
*/
private void displayNotifications() {
final List<StatusBarNotification> allNotifications = NotificationListener.getNotifications();
final List<StatusBarNotification> filteredNotifications = new ArrayList<>();
final List<Integer> notifications = new ArrayList<>();
for (final StatusBarNotification n : allNotifications) {
int singleNotificationIdentifier = getNotificationIdentifier(n.getNotification());
if (!notifications.contains(singleNotificationIdentifier)
&& ((isOnlyNotificationWithGroupKey(n, allNotifications))
|| (n.getNotification().visibility == Notification.VISIBILITY_PUBLIC
|| n.getNotification().publicVersion != null))) {
filteredNotifications.add(n);
notifications.add(singleNotificationIdentifier);
}
}
if (listView != null) {
((NotificationListAdapter) listView.getAdapter()).setNotifications(new ArrayList<>(filteredNotifications));
}
}
/**
* Check if there isn't a public notification with the same group key
*
* @param notification The notification to find a public version for
* @param allNotifications The list of all notifications
* @return True if there is no public version of the notification
*/
private boolean isOnlyNotificationWithGroupKey(final StatusBarNotification notification, final List<StatusBarNotification> allNotifications) {
if (TextUtils.isEmpty(notification.getGroupKey())) {
return true;
}
for (final StatusBarNotification singleNotification : allNotifications) {
if (!notification.equals(singleNotification) && notification.getGroupKey().equals(singleNotification.getGroupKey())) {
if ((singleNotification.getNotification().visibility == Notification.VISIBILITY_PUBLIC || singleNotification.getNotification().publicVersion != null)) {
return false;
}
}
}
return true;
}
/**
* Get an identifier for the notification based on the notifications content
*
* @param notification The notification to generate an identifier for
* @return The generated identifier
*/
private int getNotificationIdentifier(final Notification notification) {
final Date date = new Date(notification.when);
final String dateString = new SimpleDateFormat(Constants.TIME_PATTERN, Locale.GERMANY).format(date);
final Bundle extras = notification.extras;
final ApplicationInfo applicationInfo = ((ApplicationInfo) extras.get(Constants.NOTIFICATION_APP));
final String identifierString = "" + dateString + (applicationInfo != null ? applicationInfo.className : "") + extras.get(Constants.NOTIFICATION_TITLE) + extras.get(Constants.NOTIFICATION_CONTENT);
return identifierString.hashCode();
}
/**
* Get the name of the currently connected wifi
*
* @return the name of the currently connected wifi. NULL if no wifi connected
*/
private String getCurrentWifi() {
final ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final Network networks[] = connManager.getAllNetworks();
for (final Network singleNetwork : networks) {
final NetworkInfo networkInfo = connManager.getNetworkInfo(singleNetwork);
if (ConnectivityManager.TYPE_WIFI == networkInfo.getType()) {
if (!networkInfo.isConnected()) {
continue;
}
if (networkInfo.isConnected()) {
final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null) {
String ssid = connectionInfo.getSSID();
String quotes = String.valueOf('"');
if (ssid.startsWith(quotes)) {
ssid = ssid.substring(1, ssid.length());
}
if (ssid.endsWith(quotes)) {
ssid = ssid.substring(0, ssid.length() - 1);
}
return ssid;
}
}
}
}
return null;
}
/**
* Get the name of the current carrier
*
* @return A string with the carrier's name
*/
private String getCarrierName() {
final TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
final String carrierName = manager.getNetworkOperatorName();
return carrierName;
}
}
| fetch the current battery level on start. only attach broadcast manager for notifications if notifications should be displayed
| app/src/main/java/de/dreamy/DreamyDaydream.java | fetch the current battery level on start. only attach broadcast manager for notifications if notifications should be displayed | <ide><path>pp/src/main/java/de/dreamy/DreamyDaydream.java
<ide> carrierTextView.setText(getCarrierName());
<ide> }
<ide>
<add> if (settings.isShowBatteryStatus()) {
<add> updateBatteryLevel();
<add> }
<ide>
<ide> // Debug.waitForDebugger();
<ide> }
<ide> }
<ide> }
<ide>
<del>
<add> /**
<add> * {@inheritDoc}
<add> */
<ide> @Override
<ide> public void onDetachedFromWindow() {
<ide> this.unregisterReceiver(batteryBroadcastReceiver);
<ide> * new status bar notifications
<ide> */
<ide> private void initBroadcastManager() {
<del>
<del> localBroadcastManager = LocalBroadcastManager.getInstance(this);
<del>
<del> final IntentFilter filter = new IntentFilter();
<del> filter.addAction(Constants.INTENT_FILTER_NOTIFICATION_UPDATE);
<del> localBroadcastManager.registerReceiver(notificationBroadcastReceiver, filter);
<del>
<del> if (settingsDao.getSettings(this).isShowBatteryStatus()) {
<add> final Settings settings = settingsDao.getSettings(this);
<add>
<add> if (settings.isShowNotifications()) {
<add> localBroadcastManager = LocalBroadcastManager.getInstance(this);
<add> final IntentFilter filter = new IntentFilter();
<add> filter.addAction(Constants.INTENT_FILTER_NOTIFICATION_UPDATE);
<add> localBroadcastManager.registerReceiver(notificationBroadcastReceiver, filter);
<add> }
<add>
<add> if (settings.isShowBatteryStatus()) {
<ide> final IntentFilter batteryStatusIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
<ide> this.registerReceiver(batteryBroadcastReceiver, batteryStatusIntentFilter);
<ide> }
<ide> return null;
<ide> }
<ide>
<add>
<ide> /**
<ide> * Get the name of the current carrier
<ide> *
<ide> return carrierName;
<ide> }
<ide>
<add>
<add> /**
<add> * Get the current battery level and send it to the receiver
<add> *
<add> * @return
<add> */
<add> public void updateBatteryLevel() {
<add> final Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
<add> batteryBroadcastReceiver.onReceive(this, batteryIntent);
<add> }
<add>
<ide> } |
|
Java | agpl-3.0 | b24a47cc3041a0fecd961717509107994d762799 | 0 | dfsilva/actor-platform,dfsilva/actor-platform,ufosky-server/actor-platform,ufosky-server/actor-platform,EaglesoftZJ/actor-platform,ufosky-server/actor-platform,dfsilva/actor-platform,actorapp/actor-platform,dfsilva/actor-platform,actorapp/actor-platform,actorapp/actor-platform,EaglesoftZJ/actor-platform,dfsilva/actor-platform,actorapp/actor-platform,actorapp/actor-platform,dfsilva/actor-platform,actorapp/actor-platform,actorapp/actor-platform,EaglesoftZJ/actor-platform,ufosky-server/actor-platform,ufosky-server/actor-platform,EaglesoftZJ/actor-platform,dfsilva/actor-platform,dfsilva/actor-platform,actorapp/actor-platform,EaglesoftZJ/actor-platform,ufosky-server/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,ufosky-server/actor-platform,EaglesoftZJ/actor-platform,ufosky-server/actor-platform | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
package im.actor.core.entity;
import com.google.j2objc.annotations.Property;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import im.actor.core.api.ApiAvatar;
import im.actor.core.api.ApiGroup;
import im.actor.core.api.ApiMember;
import im.actor.runtime.bser.BserCreator;
import im.actor.runtime.bser.BserValues;
import im.actor.runtime.bser.BserWriter;
import im.actor.runtime.storage.KeyValueItem;
public class Group extends WrapperEntity<ApiGroup> implements KeyValueItem {
private static final int RECORD_ID = 10;
public static BserCreator<Group> CREATOR = Group::new;
@Property("readonly, nonatomic")
private int groupId;
private long accessHash;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private String title;
@Nullable
@Property("readonly, nonatomic")
private Avatar avatar;
@Property("readonly, nonatomic")
private int creatorId;
@Property("readonly, nonatomic")
private boolean isHidden;
@Nullable
@Property("readonly, nonatomic")
private String theme;
@Nullable
@Property("readonly, nonatomic")
private String about;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private List<GroupMember> members;
public Group(@NotNull ApiGroup group) {
super(RECORD_ID, group);
}
public Group(@NotNull byte[] data) throws IOException {
super(RECORD_ID, data);
}
private Group() {
super(RECORD_ID);
}
public Peer peer() {
return new Peer(PeerType.GROUP, groupId);
}
public int getGroupId() {
return groupId;
}
public long getAccessHash() {
return accessHash;
}
@NotNull
public String getTitle() {
return title;
}
@Nullable
public Avatar getAvatar() {
return avatar;
}
@NotNull
public List<GroupMember> getMembers() {
return members;
}
@Nullable
public String getTheme() {
return theme;
}
@Nullable
public String getAbout() {
return about;
}
public int getCreatorId() {
return creatorId;
}
public boolean isHidden() {
return isHidden;
}
public Group clearMembers() {
ApiGroup w = getWrapped();
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
new ArrayList<>(),
w.getCreateDate(),
w.getTheme(),
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group removeMember(int uid) {
ApiGroup w = getWrapped();
ArrayList<ApiMember> nMembers = new ArrayList<>();
for (ApiMember member : w.getMembers()) {
if (member.getUid() != uid) {
nMembers.add(member);
}
}
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
nMembers,
w.getCreateDate(),
w.getTheme(),
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group addMember(int uid, int inviterUid, long inviteDate) {
ApiGroup w = getWrapped();
ArrayList<ApiMember> nMembers = new ArrayList<>();
for (ApiMember member : w.getMembers()) {
if (member.getUid() != uid) {
nMembers.add(member);
}
}
nMembers.add(new ApiMember(uid, inviterUid, inviteDate, null));
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
nMembers,
w.getCreateDate(),
w.getTheme(),
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group updateMembers(List<ApiMember> nMembers) {
ApiGroup w = getWrapped();
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
nMembers,
w.getCreateDate(),
w.getTheme(),
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group editTitle(String title) {
ApiGroup w = getWrapped();
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
title,
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
w.getMembers(),
w.getCreateDate(),
w.getTheme(),
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group editTheme(String theme) {
ApiGroup w = getWrapped();
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
w.getMembers(),
w.getCreateDate(),
theme,
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group editAbout(String about) {
ApiGroup w = getWrapped();
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
w.getMembers(),
w.getCreateDate(),
w.getTheme(),
about);
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group editAvatar(ApiAvatar avatar) {
ApiGroup w = getWrapped();
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
avatar,
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
w.getMembers(),
w.getCreateDate(),
w.getTheme(),
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
@Override
protected void applyWrapped(@NotNull ApiGroup wrapped) {
this.groupId = wrapped.getId();
this.accessHash = wrapped.getAccessHash();
this.title = wrapped.getTitle();
this.avatar = wrapped.getAvatar() != null ? new Avatar(wrapped.getAvatar()) : null;
this.creatorId = wrapped.getCreatorUid();
this.members = new ArrayList<>();
for (ApiMember m : wrapped.getMembers()) {
this.members.add(new GroupMember(m.getUid(), m.getInviterUid(), m.getDate(), m.isAdmin() != null ? m.isAdmin() : m.getUid() == this.creatorId));
}
this.isHidden = wrapped.isHidden() != null ? wrapped.isHidden() : false;
this.about = wrapped.getAbout();
this.theme = wrapped.getTheme();
}
@Override
public void parse(BserValues values) throws IOException {
// Is Wrapper Layout
if (values.getBool(9, false)) {
// Parse wrapper layout
super.parse(values);
} else {
// Convert old layout
throw new IOException("Unsupported obsolete format");
}
}
@Override
public void serialize(BserWriter writer) throws IOException {
// Mark as wrapper layout
writer.writeBool(9, true);
// Serialize wrapper layout
super.serialize(writer);
}
@Override
public long getEngineId() {
return groupId;
}
@Override
@NotNull
protected ApiGroup createInstance() {
return new ApiGroup();
}
}
| actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/entity/Group.java | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
package im.actor.core.entity;
import com.google.j2objc.annotations.Property;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import im.actor.core.api.ApiAvatar;
import im.actor.core.api.ApiGroup;
import im.actor.core.api.ApiMember;
import im.actor.runtime.bser.BserCreator;
import im.actor.runtime.bser.BserValues;
import im.actor.runtime.bser.BserWriter;
import im.actor.runtime.storage.KeyValueItem;
public class Group extends WrapperEntity<ApiGroup> implements KeyValueItem {
private static final int RECORD_ID = 10;
public static BserCreator<Group> CREATOR = Group::new;
@Property("readonly, nonatomic")
private int groupId;
private long accessHash;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private String title;
@Nullable
@Property("readonly, nonatomic")
private Avatar avatar;
@Property("readonly, nonatomic")
private int creatorId;
@Property("readonly, nonatomic")
private boolean isHidden;
@Nullable
@Property("readonly, nonatomic")
private String theme;
@Nullable
@Property("readonly, nonatomic")
private String about;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private List<GroupMember> members;
public Group(@NotNull ApiGroup group) {
super(RECORD_ID, group);
}
public Group(@NotNull byte[] data) throws IOException {
super(RECORD_ID, data);
}
private Group() {
super(RECORD_ID);
}
public Peer peer() {
return new Peer(PeerType.GROUP, groupId);
}
public int getGroupId() {
return groupId;
}
public long getAccessHash() {
return accessHash;
}
@NotNull
public String getTitle() {
return title;
}
@Nullable
public Avatar getAvatar() {
return avatar;
}
@NotNull
public List<GroupMember> getMembers() {
return members;
}
@Nullable
public String getTheme() {
return theme;
}
@Nullable
public String getAbout() {
return about;
}
public int getCreatorId() {
return creatorId;
}
public boolean isHidden() {
return isHidden;
}
public Group clearMembers() {
ApiGroup w = getWrapped();
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
new ArrayList<>(),
w.getCreateDate(),
w.getTheme(),
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group removeMember(int uid) {
ApiGroup w = getWrapped();
ArrayList<ApiMember> nMembers = new ArrayList<>();
for (ApiMember member : w.getMembers()) {
if (member.getUid() != uid) {
nMembers.add(member);
}
}
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
nMembers,
w.getCreateDate(),
w.getTheme(),
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group addMember(int uid, int inviterUid, long inviteDate) {
ApiGroup w = getWrapped();
ArrayList<ApiMember> nMembers = new ArrayList<>();
for (ApiMember member : w.getMembers()) {
if (member.getUid() != uid) {
nMembers.add(member);
}
}
nMembers.add(new ApiMember(uid, inviterUid, inviteDate, null));
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
nMembers,
w.getCreateDate(),
w.getTheme(),
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group updateMembers(List<ApiMember> nMembers) {
ApiGroup w = getWrapped();
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
nMembers,
w.getCreateDate(),
w.getTheme(),
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group editTitle(String title) {
ApiGroup w = getWrapped();
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
title,
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
w.getMembers(),
w.getCreateDate(),
w.getTheme(),
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group editTheme(String theme) {
ApiGroup w = getWrapped();
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
w.getMembers(),
w.getCreateDate(),
theme,
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group editAbout(String about) {
ApiGroup w = getWrapped();
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
w.getMembers(),
w.getCreateDate(),
w.getTheme(),
about);
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
public Group editAvatar(ApiAvatar avatar) {
ApiGroup w = getWrapped();
ApiGroup res = new ApiGroup(
w.getId(),
w.getAccessHash(),
w.getTitle(),
w.getAvatar(),
w.getMembersCount(),
w.isMember(),
w.isHidden(),
w.getGroupType(),
w.canSendMessage(),
w.getExt(),
w.isAdmin(),
w.getCreatorUid(),
w.getMembers(),
w.getCreateDate(),
w.getTheme(),
w.getAbout());
res.setUnmappedObjects(w.getUnmappedObjects());
return new Group(res);
}
@Override
protected void applyWrapped(@NotNull ApiGroup wrapped) {
this.groupId = wrapped.getId();
this.accessHash = wrapped.getAccessHash();
this.title = wrapped.getTitle();
this.avatar = wrapped.getAvatar() != null ? new Avatar(wrapped.getAvatar()) : null;
this.creatorId = wrapped.getCreatorUid();
this.members = new ArrayList<>();
for (ApiMember m : wrapped.getMembers()) {
this.members.add(new GroupMember(m.getUid(), m.getInviterUid(), m.getDate(), m.isAdmin() != null ? m.isAdmin() : m.getUid() == this.creatorId));
}
this.isHidden = wrapped.isHidden() != null ? wrapped.isHidden() : false;
this.about = wrapped.getAbout();
this.theme = wrapped.getTheme();
}
@Override
public void parse(BserValues values) throws IOException {
// Is Wrapper Layout
if (values.getBool(9, false)) {
// Parse wrapper layout
super.parse(values);
} else {
// Convert old layout
throw new IOException("Unsupported obsolete format");
}
}
@Override
public void serialize(BserWriter writer) throws IOException {
// Mark as wrapper layout
writer.writeBool(9, true);
// Serialize wrapper layout
super.serialize(writer);
}
@Override
public long getEngineId() {
return groupId;
}
@Override
@NotNull
protected ApiGroup createInstance() {
return new ApiGroup();
}
}
| fix(core): fix editAvatar
| actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/entity/Group.java | fix(core): fix editAvatar | <ide><path>ctor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/entity/Group.java
<ide> w.getId(),
<ide> w.getAccessHash(),
<ide> w.getTitle(),
<del> w.getAvatar(),
<add> avatar,
<ide> w.getMembersCount(),
<ide> w.isMember(),
<ide> w.isHidden(), |
|
JavaScript | apache-2.0 | 9a4eb5e485ebbbf01aa1dbe84c1119e017c246b7 | 0 | dlockhart/web-caching-presentation,dlockhart/web-caching-presentation | var Diagram = require('./diagram'),
React = require('react'), // eslint-disable-line no-unused-vars
ReactDOM = require('react-dom'),
Slide = require('./slide'),
Step = require('./slide-step');
var slides = [
<Slide type="title">
<Step>
<h1>Web Caching</h1>
</Step>
<Step>
<em>Daryl McMillan and Dave Lockhart</em>
</Step>
</Slide>,
<Slide>
<h1>HTTP Headers Review</h1>
<Step>
<h2>Request</h2>
<pre className="box">
<strong>Accept:</strong> text/html,application/xhtml+xml,application/xml;<br />
<strong>Accept-Encoding:</strong> gzip, deflate, sdch<br />
<strong>Accept-Language:</strong> en-US,en;q=0.8,fr;q=0.6<br />
<strong>Cookie:</strong> blah blah<br />
<strong>Host:</strong> developer.mozilla.org<br />
<strong>User-Agent:</strong> Mozilla/5.0 (Macintosh; AppleWebKit/537.36
</pre>
</Step>
<Step>
<h2>Response</h2>
<pre className="box">
<strong>Content-Encoding:</strong> gzip<br />
<strong>Content-Type:</strong> text/html; charset=utf-8<br />
<strong>Date:</strong> Tue, 01 Dec 2015 01:50:49 GMT<br />
<strong>Last-Modified:</strong> Tue, 17 Nov 2015 20:41:07 GMT<br />
</pre>
</Step>
</Slide>,
<Slide>
<Diagram data={require('./diagrams/1-no-caching.json')} />
</Slide>,
<Slide>
<h1>Application Caching</h1>
</Slide>,
<Slide>
<Diagram data={require('./diagrams/2-app-caching.json')} />
</Slide>,
<Slide>
<h1>Output Caching</h1>
</Slide>,
<Slide>
<Diagram data={require('./diagrams/3-output-caching.json')} />
</Slide>,
<Slide>
<h1>Conditional GET</h1>
</Slide>,
<Slide>
<Diagram data={require('./diagrams/4-conditional-get.json')} />
</Slide>,
<Slide>
<h1>Cache-Control Header</h1>
<p>Talk about public vs. private and max-age.</p>
</Slide>,
<Slide>
<Diagram data={require('./diagrams/5-max-age.json')} />
</Slide>,
<Slide>
<h1>CDN</h1>
<p>Talk about what a CDN is, advantages, when to use them and the Brightspace CDN.</p>
</Slide>,
<Slide>
<Diagram data={require('./diagrams/6-all-together.json')} />
</Slide>,
<Slide>
<h1>Summary</h1>
<p>
List out a bullet of each thing learned.
</p>
</Slide>,
<Slide>
<h1>Tips</h1>
<p>
List out some additional tips.
</p>
</Slide>,
<Slide type="title">
<h1>Questions?</h1>
</Slide>
];
var Application = React.createClass({
componentDidMount: function() {
window.addEventListener('keydown', this.handleKeyPress);
},
componentWillUnmount: function() {
window.removeEventListener('keydown', this.handleKeyPress);
},
handleKeyPress: function(e) {
switch (e.keyCode) {
// up
case 38:
this.prevSlide();
break;
// down
case 40:
this.nextSlide();
break;
// left
case 37:
if (this.state.stepNum > 0) {
this.setState({stepNum: Math.max(0, --this.state.stepNum)});
}
break;
// right
case 39:
this.setState({stepNum: ++this.state.stepNum});
break;
}
},
nextSlide: function() {
var slideNum = Math.min(this.state.slideNum + 1, slides.length - 1);
if (slideNum !== this.state.slideNum) {
this.setState({slideNum: slideNum, stepNum: 0});
}
},
prevSlide: function() {
var slideNum = Math.max(0, this.state.slideNum - 1);
if (slideNum !== this.state.slideNum) {
this.setState({slideNum: slideNum, stepNum: 0});
}
},
getInitialState: function() {
return {
slideNum: 0,
stepNum: 0
};
},
render: function() {
var slide = React.cloneElement(
slides[this.state.slideNum],
{stepNum: this.state.stepNum}
);
return slide;
}
});
ReactDOM.render(
<Application />,
document.getElementById('app')
);
| src/app.js | var Diagram = require('./diagram'),
React = require('react'), // eslint-disable-line no-unused-vars
ReactDOM = require('react-dom'),
Slide = require('./slide'),
Step = require('./slide-step');
var slides = [
<Slide type="title">
<Step>
<h1>Web Caching</h1>
</Step>
<Step>
<em>Daryl McMillan and Dave Lockhart</em>
</Step>
</Slide>,
<Slide>
<h1>HTTP Headers Review</h1>
<Step>
<h2>Request</h2>
<pre className="box">
<strong>Accept:</strong> text/html,application/xhtml+xml,application/xml;<br />
<strong>Accept-Encoding:</strong> gzip, deflate, sdch<br />
<strong>Accept-Language:</strong> en-US,en;q=0.8,fr;q=0.6<br />
<strong>Cookie:</strong> blah blah<br />
<strong>Host:</strong> developer.mozilla.org<br />
<strong>User-Agent:</strong> Mozilla/5.0 (Macintosh; AppleWebKit/537.36
</pre>
</Step>
<Step>
<h2>Response</h2>
<pre className="box">
<strong>Content-Encoding:</strong> gzip<br />
<strong>Content-Type:</strong> text/html; charset=utf-8<br />
<strong>Date:</strong> Tue, 01 Dec 2015 01:50:49 GMT<br />
<strong>Last-Modified:</strong> Tue, 17 Nov 2015 20:41:07 GMT<br />
</pre>
</Step>
</Slide>,
<Slide>
<Diagram data={require('./diagrams/1-no-caching.json')} />
</Slide>,
<Slide>
<h1>Application Caching</h1>
</Slide>,
<Slide>
<Diagram data={require('./diagrams/2-app-caching.json')} />
</Slide>,
<Slide>
<h1>Output Caching</h1>
</Slide>,
<Slide>
<Diagram data={require('./diagrams/3-output-caching.json')} />
</Slide>,
<Slide>
<h1>Conditional GET</h1>
</Slide>,
<Slide>
<Diagram data={require('./diagrams/4-conditional-get.json')} />
</Slide>,
<Slide>
<h1>Cache-Control Header</h1>
<p>Talk about public vs. private and max-age.</p>
</Slide>,
<Slide>
<Diagram data={require('./diagrams/5-max-age.json')} />
</Slide>,
<Slide>
<h1>CDN</h1>
<p>Talk about what a CDN is, advantages, when to use them and the Brightspace CDN.</p>
</Slide>,
<Slide>
<Diagram data={require('./diagrams/6-all-together.json')} />
</Slide>
];
var Application = React.createClass({
componentDidMount: function() {
window.addEventListener('keydown', this.handleKeyPress);
},
componentWillUnmount: function() {
window.removeEventListener('keydown', this.handleKeyPress);
},
handleKeyPress: function(e) {
switch (e.keyCode) {
// up
case 38:
this.prevSlide();
break;
// down
case 40:
this.nextSlide();
break;
// left
case 37:
if (this.state.stepNum > 0) {
this.setState({stepNum: Math.max(0, --this.state.stepNum)});
}
break;
// right
case 39:
this.setState({stepNum: ++this.state.stepNum});
break;
}
},
nextSlide: function() {
var slideNum = Math.min(this.state.slideNum + 1, slides.length - 1);
if (slideNum !== this.state.slideNum) {
this.setState({slideNum: slideNum, stepNum: 0});
}
},
prevSlide: function() {
var slideNum = Math.max(0, this.state.slideNum - 1);
if (slideNum !== this.state.slideNum) {
this.setState({slideNum: slideNum, stepNum: 0});
}
},
getInitialState: function() {
return {
slideNum: 0,
stepNum: 0
};
},
render: function() {
var slide = React.cloneElement(
slides[this.state.slideNum],
{stepNum: this.state.stepNum}
);
return slide;
}
});
ReactDOM.render(
<Application />,
document.getElementById('app')
);
| placeholder slides for summary, tips and questions
| src/app.js | placeholder slides for summary, tips and questions | <ide><path>rc/app.js
<ide> </Slide>,
<ide> <Slide>
<ide> <Diagram data={require('./diagrams/6-all-together.json')} />
<add> </Slide>,
<add> <Slide>
<add> <h1>Summary</h1>
<add> <p>
<add> List out a bullet of each thing learned.
<add> </p>
<add> </Slide>,
<add> <Slide>
<add> <h1>Tips</h1>
<add> <p>
<add> List out some additional tips.
<add> </p>
<add> </Slide>,
<add> <Slide type="title">
<add> <h1>Questions?</h1>
<ide> </Slide>
<ide> ];
<ide> |
|
Java | mit | 806b8432af996d9f54d24251223c77cb8a47b218 | 0 | wzgiceman/RxjavaRetrofitDemo-string-master,wzgiceman/RxjavaRetrofitDemo-string-master | package com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception;
/**
* 运行时自定义错误信息
* 自由添加错误,需要自己扩展
* Created by WZG on 2016/7/16.
*/
public class HttpTimeException extends RuntimeException {
/*未知错误*/
public static final int UNKOWN_ERROR = 0x1002;
/*本地无缓存错误*/
public static final int NO_CHACHE_ERROR = 0x1003;
/*缓存过时错误*/
public static final int CHACHE_TIMEOUT_ERROR = 0x1004;
public HttpTimeException(int resultCode) {
this(getApiExceptionMessage(resultCode));
}
public HttpTimeException(String detailMessage) {
super(detailMessage);
}
/**
* 转换错误数据
*
* @param code
* @return
*/
private static String getApiExceptionMessage(int code) {
switch (code) {
case UNKOWN_ERROR:
return "错误:网络错误";
case NO_CHACHE_ERROR:
return "错误:无缓存数据";
case CHACHE_TIMEOUT_ERROR:
return "错误:缓存数据过期";
default:
return "错误:未知错误";
}
}
}
| rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/HttpTimeException.java | package com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception;
/**
* 运行时自定义错误信息
* 自由添加错误,需要自己扩展
* Created by WZG on 2016/7/16.
*/
public class HttpTimeException extends RuntimeException {
/*未知错误*/
public static final int UNKOWN_ERROR = 0x1002;
/*本地无缓存错误*/
public static final int NO_CHACHE_ERROR = 0x1003;
/*缓存过去错误*/
public static final int CHACHE_TIMEOUT_ERROR = 0x1004;
public HttpTimeException(int resultCode) {
this(getApiExceptionMessage(resultCode));
}
public HttpTimeException(String detailMessage) {
super(detailMessage);
}
/**
* 转换错误数据
*
* @param code
* @return
*/
private static String getApiExceptionMessage(int code) {
switch (code) {
case UNKOWN_ERROR:
return "错误:网络错误";
case NO_CHACHE_ERROR:
return "错误:无缓存数据";
case CHACHE_TIMEOUT_ERROR:
return "错误:缓存数据过期";
default:
return "错误:未知错误";
}
}
}
| 加入异常的统一判断
版本信息2.0
| rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/HttpTimeException.java | 加入异常的统一判断 版本信息2.0 | <ide><path>xretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/HttpTimeException.java
<ide> public static final int UNKOWN_ERROR = 0x1002;
<ide> /*本地无缓存错误*/
<ide> public static final int NO_CHACHE_ERROR = 0x1003;
<del> /*缓存过去错误*/
<add> /*缓存过时错误*/
<ide> public static final int CHACHE_TIMEOUT_ERROR = 0x1004;
<ide>
<ide> |
|
JavaScript | mit | be971fb69ebc7b95a5e554330fc48133dacf59d3 | 0 | fadieh/javascript_rockpaperscissors | describe('Rock Paper Scissors', function () {
// // // // // // // GESTURES TEST // // // // // // //
describe('Gestures', function () {
it ('Rock', function () {
rock = new Rock
expect(rock.type).toEqual('Rock')
});
it ('Scissors', function (){
scissors = new Scissors
expect(scissors.type).toEqual('Scissors')
});
it ('Paper', function () {
paper = new Paper
expect(paper.type).toEqual('Paper')
});
});
// // // // // // // RULES TEST // // // // // // //
describe('Rules', function () {
});
}); | spec/rockpaperscissors_spec.js | describe('Rock Paper Scissors', function () {
describe('Gestures', function () {
it ('Rock', function () {
rock = new Rock
expect(rock.type).toEqual('Rock')
})
it ('Scissors', function (){
scissors = new Scissors
expect(scissors.type).toEqual('Scissors')
})
it ('Paper', function () {
paper = new Paper
expect(paper.type).toEqual('Paper')
})
})
}) | Added rules testing
| spec/rockpaperscissors_spec.js | Added rules testing | <ide><path>pec/rockpaperscissors_spec.js
<ide> describe('Rock Paper Scissors', function () {
<add>
<add>// // // // // // // GESTURES TEST // // // // // // //
<ide>
<ide> describe('Gestures', function () {
<ide>
<ide> it ('Rock', function () {
<ide> rock = new Rock
<ide> expect(rock.type).toEqual('Rock')
<del> })
<add> });
<ide>
<ide> it ('Scissors', function (){
<ide> scissors = new Scissors
<ide> expect(scissors.type).toEqual('Scissors')
<del> })
<add> });
<ide>
<ide> it ('Paper', function () {
<ide> paper = new Paper
<ide> expect(paper.type).toEqual('Paper')
<del> })
<add> });
<ide>
<del> })
<add> });
<add>
<add>// // // // // // // RULES TEST // // // // // // //
<add>
<add> describe('Rules', function () {
<add>
<add> });
<ide>
<ide>
<del>})
<add>}); |
|
JavaScript | mit | 378337eec1cd298da5e0b0ce2e5c75a83d48a5cd | 0 | locaweb/locawebstyle,diegoeis/locawebstyle,diegoeis/locawebstyle,deividmarques/locawebstyle,MaizerGomes/locawebstyle,EveraldoReis/locawebstyle,MaizerGomes/locawebstyle,kemelzaidan/locawebstyle,kemelzaidan/locawebstyle,EveraldoReis/locawebstyle,locaweb/locawebstyle,deividmarques/locawebstyle,EveraldoReis/locawebstyle,kemelzaidan/locawebstyle,locaweb/locawebstyle,diegoeis/locawebstyle,deividmarques/locawebstyle,MaizerGomes/locawebstyle | describe("Popover: ", function() {
beforeEach(function() {
loadFixtures('popover_fixture.html');
locastyle.popover.init();
});
afterEach(function() {
locastyle.popover.destroyPopover();
});
describe("Popover creation", function() {
it("Should create a popover on click event", function() {
// Added as pending because the tests broke while I was testing other functionality
$('#popoverclick[data-ls-module="popover"]').trigger("click");
expect($(".ls-popover")).toBeVisible();
});
it("Should create a popover on hover event", function() {
// Added as pending because the tests broke while I was testing other functionality
$('[data-ls-module="popover"]').trigger("mouseenter");
expect($(".ls-popover")).toBeVisible();
});
});
describe("After popover created", function() {
it("Should remove popover on click event", function() {
$('[data-ls-module="popover"]').trigger("click");
expect($("#mypopovervisible .ls-popover")).not.toExist();
});
it("Should remove popover on mouseleave of element", function() {
$('[data-ls-module="popover"]').trigger("mouseleave");
expect($("#mypopovervisible .ls-popover")).not.toExist();
});
it("should oepn popover when event ls.popoverOpen is triggered", function() {
$('[data-ls-module="popover"]').trigger("ls.popoverOpen");
expect($(".ls-popover")).toBeVisible();
});
});
describe("[unbind] When init is called multiple times", function () {
it("should bind events on popover elements only one time", function () {
locastyle.init();
locastyle.init();
locastyle.init();
// clean prevent default events
$("a").off("click.lsPreventDefault");
expect($("[data-ls-module='popover']")).toHaveBeenBindedOnce("click");
});
it("should bind events on popover elements only one time", function () {
locastyle.init();
locastyle.popover.init();
locastyle.popover.init();
expect($("#mouseenterbinded")).toHaveBeenBindedOnce("mouseout");
});
it("should bind events for breakpoint only one time", function () {
locastyle.init();
locastyle.popover.init();
locastyle.popover.init();
expect($(document)).toHaveBeenBindedOnce("breakpoint-updated");
});
});
});
| spec/javascripts/popover_spec.js | describe("Popover: ", function() {
beforeEach(function() {
loadFixtures('popover_fixture.html');
locastyle.popover.init();
});
afterEach(function() {
locastyle.popover.destroyPopover();
});
describe("Popover creation", function() {
it("Should create a popover on click event", function() {
// Added as pending because the tests broke while I was testing other functionality
$('#popoverclick[data-ls-module="popover"]').trigger("click");
expect($(".ls-popover")).toBeVisible();
});
it("Should create a popover on hover event", function() {
// Added as pending because the tests broke while I was testing other functionality
$('[data-ls-module="popover"]').trigger("mouseenter");
expect($(".ls-popover")).toBeVisible();
});
});
describe("After popover created", function() {
it("Should remove popover on click event", function() {
$('[data-ls-module="popover"]').trigger("click");
expect($("#mypopovervisible .ls-popover")).not.toExist();
});
it("Should remove popover on mouseleave of element", function() {
$('[data-ls-module="popover"]').trigger("mouseleave");
expect($("#mypopovervisible .ls-popover")).not.toExist();
});
});
describe("[unbind] When init is called multiple times", function () {
it("should bind events on popover elements only one time", function () {
locastyle.init();
locastyle.init();
locastyle.init();
// clean prevent default events
$("a").off("click.lsPreventDefault");
expect($("[data-ls-module='popover']")).toHaveBeenBindedOnce("click");
});
it("should bind events on popover elements only one time", function () {
locastyle.init();
locastyle.popover.init();
locastyle.popover.init();
expect($("#mouseenterbinded")).toHaveBeenBindedOnce("mouseout");
});
it("should bind events for breakpoint only one time", function () {
locastyle.init();
locastyle.popover.init();
locastyle.popover.init();
expect($(document)).toHaveBeenBindedOnce("breakpoint-updated");
});
});
});
| test custom event to open popover | spec/javascripts/popover_spec.js | test custom event to open popover | <ide><path>pec/javascripts/popover_spec.js
<ide> expect($("#mypopovervisible .ls-popover")).not.toExist();
<ide> });
<ide>
<add> it("should oepn popover when event ls.popoverOpen is triggered", function() {
<add> $('[data-ls-module="popover"]').trigger("ls.popoverOpen");
<add> expect($(".ls-popover")).toBeVisible();
<add> });
<add>
<ide> });
<ide>
<ide> describe("[unbind] When init is called multiple times", function () { |
|
JavaScript | bsd-2-clause | f5ed42bc50fbcf198e1b71865df1831d9237c68c | 0 | psychobunny/nodebb-plugin-cash,Linux-statt-Windows/nodebb-plugin-cash,rbeer/nodebb-plugin-cash | var fs = require('fs'),
path = require('path'),
nconf = require('nconf'),
meta = require('../../src/meta'),
user = require('../../src/user'),
websockets = require('../../src/socket.io/index.js'),
templates = module.parent.require('templates.js');
var constants = Object.freeze({
'name': "Cash MOD",
'admin': {
'route': '/cash',
'icon': 'fa-money'
},
'defaults': {
'pay_per_character': 0.25,
'currency_name': 'gp'
}
});
var Cash = {};
function renderAdmin(req, res, next) {
if (res.locals.isAPI) {
res.json({});
} else {
res.render('admin/cash', {});
}
}
function getCash(req, res, next) {
user.getUserField(req.user.uid, 'currency', function(err, points) {
res.json({
currency: meta.config['cash:currency_name'] || 'points',
points: points || 0
});
});
}
Cash.init = function(params, callback) {
var app = params.router,
middleware = params.middleware,
controllers = params.controllers;
app.get('/admin/cash', middleware.admin.buildHeader, renderAdmin);
app.get('/api/admin/cash', renderAdmin);
app.get('/api/cash', middleware.authenticate, getCash);
callback();
};
Cash.addAdminNavigation = function(custom_header, callback) {
custom_header.plugins.push({
"route": constants.admin.route,
"icon": constants.admin.icon,
"name": constants.name
});
callback(null, custom_header);
};
Cash.addProfileInfo = function(profileInfo, callback) {
var currency_name = meta.config['cash:currency_name'] || constants.defaults.currency_name;
user.getUserField(profileInfo.uid, 'currency', function(err, data) {
profileInfo.profile.push({
content: "<span class='cash-mod-currency'><img src='" + nconf.get('url') + "./plugins/nodebb-plugin-cash/static/coin1.png' /> " + (data || 0) + " " + currency_name + "</span>"
});
callback(err, profileInfo);
});
};
Cash.increaseCurrencyByPostData = function(postData) {
var multiplier = meta.config['cash:pay_per_character'] || constants.defaults.pay_per_character,
uid = postData.uid,
postLength = postData.content.length,
value = Math.floor(multiplier * postLength);
user.incrementUserFieldBy(uid, 'currency', value);
setTimeout(function() {
websockets.in('uid_' + uid).emit('event:alert', {
alert_id: 'currency_increased',
message: 'You earned <strong>' + value + ' gold</strong> for posting',
type: 'info',
timeout: 2500
});
}, 750);
};
module.exports = Cash;
| library.js | var fs = require('fs'),
path = require('path'),
nconf = require('nconf'),
meta = require('../../src/meta'),
user = require('../../src/user'),
websockets = require('../../src/socket.io/index.js'),
templates = module.parent.require('templates.js');
var constants = Object.freeze({
'name': "Cash MOD",
'admin': {
'route': '/cash',
'icon': 'fa-money'
},
'defaults': {
'pay_per_character': 0.25,
'currency_name': 'gp'
}
});
var Cash = {};
function renderAdmin(req, res, next) {
if (res.locals.isAPI) {
res.json({});
} else {
res.render('admin/cash', {});
}
}
function getCash(req, res, next) {
user.getUserField(req.user.uid, 'currency', function(err, points) {
res.json({
currency: meta.config['cash:currency_name'] || 'points',
points: points || 0
});
});
}
Cash.init = function(params, callback) {
var app = params.app,
middleware = params.middleware,
controllers = params.controllers;
app.get('/admin/cash', middleware.admin.buildHeader, renderAdmin);
app.get('/api/admin/cash', renderAdmin);
app.get('/api/cash', middleware.authenticate, getCash);
callback();
};
Cash.addAdminNavigation = function(custom_header, callback) {
custom_header.plugins.push({
"route": constants.admin.route,
"icon": constants.admin.icon,
"name": constants.name
});
callback(null, custom_header);
};
Cash.addProfileInfo = function(profileInfo, callback) {
var currency_name = meta.config['cash:currency_name'] || constants.defaults.currency_name;
user.getUserField(profileInfo.uid, 'currency', function(err, data) {
profileInfo.profile.push({
content: "<span class='cash-mod-currency'><img src='" + nconf.get('url') + "./plugins/nodebb-plugin-cash/static/coin1.png' /> " + (data || 0) + " " + currency_name + "</span>"
});
callback(err, profileInfo);
});
};
Cash.increaseCurrencyByPostData = function(postData) {
var multiplier = meta.config['cash:pay_per_character'] || constants.defaults.pay_per_character,
uid = postData.uid,
postLength = postData.content.length,
value = Math.floor(multiplier * postLength);
user.incrementUserFieldBy(uid, 'currency', value);
setTimeout(function() {
websockets.in('uid_' + uid).emit('event:alert', {
alert_id: 'currency_increased',
message: 'You earned <strong>' + value + ' gold</strong> for posting',
type: 'info',
timeout: 2500
});
}, 750);
};
module.exports = Cash;
| fixed router issue
| library.js | fixed router issue | <ide><path>ibrary.js
<ide> }
<ide>
<ide> Cash.init = function(params, callback) {
<del> var app = params.app,
<add> var app = params.router,
<ide> middleware = params.middleware,
<ide> controllers = params.controllers;
<ide> |
|
JavaScript | mit | 578beefb197abcb0c7605cec078733c56e757960 | 0 | bogoquiz/trendtwitter,bogoquiz/trendtwitter,bogoquiz/trendtwitter | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Customer = mongoose.model('Customer'),
_ = require('lodash'),
Twitter = require('twitter'),
config = require('../../config/config'),
User = mongoose.model('User'),
Country = mongoose.model('Country'),
passport = require('passport');
/**
* Create a Customer
*/
exports.create = function(req, res) {
var customer = new Customer(req.body);
customer.user = req.user;
customer.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(customer);
}
});
};
exports.create2 = function(data, user) {
for (var i = data.items.length - 1; i >= 0; i--) {
//Things[i]
var customer = new Customer({videos: data.items[i], user: user});
//customer.user = req.user;
customer.save(function(err) {
if (err) {
console.log('pailas',err);
} else {
console.log('super');
}
}
);
}
};
/**
* Show the current Customer
*/
exports.read = function(req, res) {
res.jsonp(req.customer);
};
/**
* Update a Customer
*/
exports.update = function(req, res) {
var customer = req.customer ;
customer = _.extend(customer , req.body);
customer.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(customer);
}
});
};
/**
* Delete an Customer
*/
exports.delete = function(req, res) {
var customer = req.customer ;
customer.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(customer);
}
});
};
/**
* List of Customers
*/
/*
exports.list = function(req, res) {
Customer.find().sort('-created').populate('user', 'displayName').exec(function(err, customers) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(customers);
}
});
};
*/
exports.list = function(req, res) {
var sort;
var sortObject = {};
var count = req.query.count || 5;
var page = req.query.page || 1;
var filter = {
filters : {
mandatory : {
contains: req.query.filter
}
}
};
var pagination = {
start : (page - 1) * count,
count: count
};
if(req.query.sorting){
var sortKey = Object.keys(req.query.sorting)[0];
var sortValue = req.query.sorting[sortKey];
sortObject[sortValue] = sortKey;
} else{
sortObject['desc'] = '_id';
}
var sort = {
sort: sortObject
};
Customer
.find({user: req.user})
.filter(filter)
.order(sort)
.page(pagination, function(err, customers){
if(err){
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else{
var country = [],
tokens = [],
videos = customers;
//User.find({provider: 'twitter'}, function(err, providerData){
/*tokens = providerData;
//console.dir(item);
//console.log('que pasa ' + country[1].providerData.token);
var client = new Twitter({
consumer_key: config.twitter.clientID,
consumer_secret: config.twitter.clientSecret,
access_token_key: tokens[0].providerData.token,
access_token_secret: tokens[0].providerData.tokenSecret
});
client.get('/trends/available', function(err, payload){
//console.log(payload);
if(err){
throw err;
} */
/*var b=0;
for (i = 0; i < payload.length; i++) {
if (payload[i].placeType.name === 'Country' && (payload[i].country) !== null){
country[b] = {'country': payload[i].country, 'woeid': payload[i].woeid};
b=b+1;
}
}*/
Country.find(function(err, country){
var socketio = req.app.get('socketio'); // tacke out socket instance from the app container
console.log(country);
socketio.sockets.emit('article.created', country); // emit an event for all connected clients
});
//var socketio = req.app.get('socketio'); // tacke out socket instance from the app container
//console.log(country);
// socketio.sockets.emit('article.created', country); // emit an event for all connected clients
/*
socketio.on('connection', function(socket) {
console.log('esto llego');
socket.on('countryenv', function(data) {
console.log('entro!!!' + data);
});
});*/
var item = { item1: 'Tweet dupiclate or more than 140 characters',
item2: 'Tweet dupiclate or more than 140 characters',
item3: 'Tweet dupiclate or more than 140 characters'};
for (var i = videos.results.length - 1; i >= 0; i--) {
videos.results[i].videos.kind = (videos.results[i].videos.kind,item);
}
//customers.results = {};
//customers.results = videos.results = customers.results[0].videos.items;
//console.log(customers);
//return customers;
res.jsonp(videos);
//return customers;
//});
//});
}
});
};
/**
* Customer middleware
*/
exports.customerByID = function(req, res, next, id) {
Customer.findById(id).populate('user', 'displayName').exec(function(err, customer) {
if (err) return next(err);
if (! customer) return next(new Error('Failed to load Customer ' + id));
req.customer = customer ;
next();
});
};
/**
* Customer authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.customer.user.id !== req.user.id) {
return res.status(403).send('User is not authorized');
}
next();
};
//var country;
exports.countryTwitter = function(data, user, socket) {
var country = '',
params = '',
tokens = [],
i;
User.find({provider: 'twitter', _id: user}, function(err, providerData){
tokens = providerData;
//console.dir(item);
//console.log(providerData.providerData.token);
var client = new Twitter({
consumer_key: config.twitter.clientID,
consumer_secret: config.twitter.clientSecret,
access_token_key: providerData[0].providerData.token,
access_token_secret: providerData[0].providerData.tokenSecret
});
client.get('/trends/place',{id: data}, function(err, payload){
//console.log(payload[0].trends.length);
if(err){
throw err;
} else {
for (var i = 0 ; i < payload[0].trends.length; i++) {
//mensaje.text(data[0].trends[i].name);
country = country + payload[0].trends[i].name + ' ';
}
}
socket.emit('trendenv',country);
//country = payload;
//console.log(payload);
//console.log(country[0].trends);
//module.exports.myObj = country;
});
});
//return tokens;
};
exports.sendTwitter = function(data, user, socket) {
User.find({provider: 'twitter', _id: user}, function(err, providerData){
var client = new Twitter({
consumer_key: config.twitter.clientID,
consumer_secret: config.twitter.clientSecret,
access_token_key: providerData[0].providerData.token,
access_token_secret: providerData[0].providerData.tokenSecret
});
//console.log(providerData[1]+' data');
client.post('statuses/update', {status: data }, function(error, data,response){
//if(error) throw error; h º1GVGVGVGVGVGVGVBHGJHJKHJH
if(!error){
console.log('Tweet enviado',error); // Tweet body.
socket.emit('mensagge','send');
}else{
socket.emit('mensagge',error);
console.log('error',error);
}
//console.log(response);
//console.log(response); // Raw response object.
});
});
};
exports.twitterBucle = function (user){
var trend = ' ';
console.log(user);
Country.find(function(err, country){
console.log(country[0].country[3].woeid);
User.find({provider: 'twitter', _id: user}, function(err, providerData){
//console.log('EMPEZO');
var client = new Twitter({
consumer_key: config.twitter.clientID,
consumer_secret: config.twitter.clientSecret,
access_token_key: providerData[0].providerData.token,
access_token_secret: providerData[0].providerData.tokenSecret
});
var x = 0,
y = 0,
z = 0;
//console.log(y);
setInterval(function() {
if (x < country[0].country.length) {
client.get('/trends/place',{id: country[0].country[x].woeid}, function(err, payload){
//client.get('/trends/place',{id: 23424757}, function(err, payload){
//console.log(payload[0].trends[1].name);
//console.log(payload[0]);
if(!err){
//console.log(payload[0].trends[1].name); // Tweet body.
for (var i = 0 ; i < 4; i++) {
//mensaje.text(data[0].trends[i].name);
trend = trend + payload[0].trends[i].name + ' ';
}
//client.post('statuses/update', {status: payload[0].trends[1].name }, function(error, data,response){
//console.log(trend);
z= trend;
Customer.find({user: user}, function(err, links){
if (x<links.length){
trend = trend + ' http://trendmedia.herokuapp.com #FAIL' + ' http://youtu.be/' + links[35].videos.id.videoId;
}else{
trend = trend + ' http://youtu.be/' + links[35].videos.id.videoId;
//trend = trend + ' http://trendmedia.herokuapp.com';
}
// console.log(' post ', trend);
client.post('statuses/update', {status: trend }, function(error, data,response){
//if(error) throw error; h º1GVGVGVGVGVGVGVBHGJHJKHJH
if(!error){
//console.log('Tweet enviado',error); // Tweet body.
y=0;
//continue
}else{
//console.log('error post',error);
y=0;
//continue
}
//console.log(response);
//console.log(response); // Raw response object.
trend = '';
});
for (var i = 1 ; i < 2; i++) {
z = payload[0].trends[i].name + ' http://trendmedia.herokuapp.com #FAIL' + ' http://youtu.be/' + links[35].videos.id.videoId;
client.post('statuses/update', {status: z }, function(error, data,response){
//if(error) throw error; h º1GVGVGVGVGVGVGVBHGJHJKHJH
if(!error){
//console.log('Tweet enviado',error); // Tweet body.
y=0;
//continue
}else{
//console.log('error post',error);
y=0;
//continue
}
//console.log(response);
//console.log(response); // Raw response object.
//trend = '';
});
}
});
//y = Math.floor(Math.random() * (35-30+1)) + 30;
}else{
//console.log('error get',err);
y=0;
}
});
}
//else return;
if(x===country[0].country.length){
x=0;
}
x++;
//console.log(x);
}, 15000 /* (Math.floor(Math.random() * (30-20+1)) + 20)*/);
});
});
};
/*
exports.countryTwitter = function(req, res) {
//console.info('XXXXX ' + TwitterStrategy);
//console.log('kkkkkk' + users);
//User.find({provider: 'twitter'}).limit(1);
var country = [],
tokens = [],
i;
User.find({provider: 'twitter'}, function(err, providerData){
//console.log('Find: ' + providerData);
tokens = providerData;
//console.dir(item);
//console.log('que pasa ' + country[1].providerData.token);
var client = new Twitter({
consumer_key: config.twitter.clientID,
consumer_secret: config.twitter.clientSecret,
access_token_key: tokens[1].providerData.token,
access_token_secret: tokens[1].providerData.tokenSecret
});
client.get('/trends/available', function(err, payload){
var b=0;
for (i = 0; i < payload.length; i++) {
if (payload[i].placeType.name === 'Country' && (payload[i].country) !== null){
country[b] = {"country": payload[i].country, "woeid": payload[i].woeid};
//country.country[i] = {'country' : payload[i].country, 'woeid' : payload[i].woeid};
//country.woeid[i] = payload[i].woeid;
b=b+1;
}
}
console.info(country);
res.jsonp(country);
});
});
};*/
| app/controllers/customers.server.controller.js | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Customer = mongoose.model('Customer'),
_ = require('lodash'),
Twitter = require('twitter'),
config = require('../../config/config'),
User = mongoose.model('User'),
Country = mongoose.model('Country'),
passport = require('passport');
/**
* Create a Customer
*/
exports.create = function(req, res) {
var customer = new Customer(req.body);
customer.user = req.user;
customer.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(customer);
}
});
};
exports.create2 = function(data, user) {
for (var i = data.items.length - 1; i >= 0; i--) {
//Things[i]
var customer = new Customer({videos: data.items[i], user: user});
//customer.user = req.user;
customer.save(function(err) {
if (err) {
console.log('pailas',err);
} else {
console.log('super');
}
}
);
}
};
/**
* Show the current Customer
*/
exports.read = function(req, res) {
res.jsonp(req.customer);
};
/**
* Update a Customer
*/
exports.update = function(req, res) {
var customer = req.customer ;
customer = _.extend(customer , req.body);
customer.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(customer);
}
});
};
/**
* Delete an Customer
*/
exports.delete = function(req, res) {
var customer = req.customer ;
customer.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(customer);
}
});
};
/**
* List of Customers
*/
/*
exports.list = function(req, res) {
Customer.find().sort('-created').populate('user', 'displayName').exec(function(err, customers) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(customers);
}
});
};
*/
exports.list = function(req, res) {
var sort;
var sortObject = {};
var count = req.query.count || 5;
var page = req.query.page || 1;
var filter = {
filters : {
mandatory : {
contains: req.query.filter
}
}
};
var pagination = {
start : (page - 1) * count,
count: count
};
if(req.query.sorting){
var sortKey = Object.keys(req.query.sorting)[0];
var sortValue = req.query.sorting[sortKey];
sortObject[sortValue] = sortKey;
} else{
sortObject['desc'] = '_id';
}
var sort = {
sort: sortObject
};
Customer
.find({user: req.user})
.filter(filter)
.order(sort)
.page(pagination, function(err, customers){
if(err){
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else{
var country = [],
tokens = [],
videos = customers;
//User.find({provider: 'twitter'}, function(err, providerData){
/*tokens = providerData;
//console.dir(item);
//console.log('que pasa ' + country[1].providerData.token);
var client = new Twitter({
consumer_key: config.twitter.clientID,
consumer_secret: config.twitter.clientSecret,
access_token_key: tokens[0].providerData.token,
access_token_secret: tokens[0].providerData.tokenSecret
});
client.get('/trends/available', function(err, payload){
//console.log(payload);
if(err){
throw err;
} */
/*var b=0;
for (i = 0; i < payload.length; i++) {
if (payload[i].placeType.name === 'Country' && (payload[i].country) !== null){
country[b] = {'country': payload[i].country, 'woeid': payload[i].woeid};
b=b+1;
}
}*/
Country.find(function(err, country){
var socketio = req.app.get('socketio'); // tacke out socket instance from the app container
console.log(country);
socketio.sockets.emit('article.created', country); // emit an event for all connected clients
});
//var socketio = req.app.get('socketio'); // tacke out socket instance from the app container
//console.log(country);
// socketio.sockets.emit('article.created', country); // emit an event for all connected clients
/*
socketio.on('connection', function(socket) {
console.log('esto llego');
socket.on('countryenv', function(data) {
console.log('entro!!!' + data);
});
});*/
var item = { item1: 'Tweet dupiclate or more than 140 characters',
item2: 'Tweet dupiclate or more than 140 characters',
item3: 'Tweet dupiclate or more than 140 characters'};
for (var i = videos.results.length - 1; i >= 0; i--) {
videos.results[i].videos.kind = (videos.results[i].videos.kind,item);
}
//customers.results = {};
//customers.results = videos.results = customers.results[0].videos.items;
//console.log(customers);
//return customers;
res.jsonp(videos);
//return customers;
//});
//});
}
});
};
/**
* Customer middleware
*/
exports.customerByID = function(req, res, next, id) {
Customer.findById(id).populate('user', 'displayName').exec(function(err, customer) {
if (err) return next(err);
if (! customer) return next(new Error('Failed to load Customer ' + id));
req.customer = customer ;
next();
});
};
/**
* Customer authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.customer.user.id !== req.user.id) {
return res.status(403).send('User is not authorized');
}
next();
};
//var country;
exports.countryTwitter = function(data, user, socket) {
var country = '',
params = '',
tokens = [],
i;
User.find({provider: 'twitter', _id: user}, function(err, providerData){
tokens = providerData;
//console.dir(item);
//console.log(providerData.providerData.token);
var client = new Twitter({
consumer_key: config.twitter.clientID,
consumer_secret: config.twitter.clientSecret,
access_token_key: providerData[0].providerData.token,
access_token_secret: providerData[0].providerData.tokenSecret
});
client.get('/trends/place',{id: data}, function(err, payload){
//console.log(payload[0].trends.length);
if(err){
throw err;
} else {
for (var i = 0 ; i < payload[0].trends.length; i++) {
//mensaje.text(data[0].trends[i].name);
country = country + payload[0].trends[i].name + ' ';
}
}
socket.emit('trendenv',country);
//country = payload;
//console.log(payload);
//console.log(country[0].trends);
//module.exports.myObj = country;
});
});
//return tokens;
};
exports.sendTwitter = function(data, user, socket) {
User.find({provider: 'twitter', _id: user}, function(err, providerData){
var client = new Twitter({
consumer_key: config.twitter.clientID,
consumer_secret: config.twitter.clientSecret,
access_token_key: providerData[0].providerData.token,
access_token_secret: providerData[0].providerData.tokenSecret
});
//console.log(providerData[1]+' data');
client.post('statuses/update', {status: data }, function(error, data,response){
//if(error) throw error; h º1GVGVGVGVGVGVGVBHGJHJKHJH
if(!error){
console.log('Tweet enviado',error); // Tweet body.
socket.emit('mensagge','send');
}else{
socket.emit('mensagge',error);
console.log('error',error);
}
//console.log(response);
//console.log(response); // Raw response object.
});
});
};
exports.twitterBucle = function (user){
var trend = ' ';
console.log(user);
Country.find(function(err, country){
console.log(country[0].country[3].woeid);
User.find({provider: 'twitter', _id: user}, function(err, providerData){
//console.log('EMPEZO');
var client = new Twitter({
consumer_key: config.twitter.clientID,
consumer_secret: config.twitter.clientSecret,
access_token_key: providerData[0].providerData.token,
access_token_secret: providerData[0].providerData.tokenSecret
});
var x = 0,
y = 0,
z = 0;
//console.log(y);
setInterval(function() {
if (x < country[0].country.length) {
client.get('/trends/place',{id: country[0].country[x].woeid}, function(err, payload){
//client.get('/trends/place',{id: 23424757}, function(err, payload){
//console.log(payload[0].trends[1].name);
//console.log(payload[0]);
if(!err){
//console.log(payload[0].trends[1].name); // Tweet body.
for (var i = 0 ; i < 4; i++) {
//mensaje.text(data[0].trends[i].name);
trend = trend + payload[0].trends[i].name + ' ';
}
//client.post('statuses/update', {status: payload[0].trends[1].name }, function(error, data,response){
//console.log(trend);
z= trend;
Customer.find({user: user}, function(err, links){
if (x<links.length){
trend = trend + ' http://trendmedia.herokuapp.com #FAIL' + ' http://youtu.be/' + links[x].videos.id.videoId;
}else{
trend = trend + ' http://youtu.be/' + links[35].videos.id.videoId;
//trend = trend + ' http://trendmedia.herokuapp.com';
}
// console.log(' post ', trend);
client.post('statuses/update', {status: trend }, function(error, data,response){
//if(error) throw error; h º1GVGVGVGVGVGVGVBHGJHJKHJH
if(!error){
//console.log('Tweet enviado',error); // Tweet body.
y=0;
//continue
}else{
//console.log('error post',error);
y=0;
//continue
}
//console.log(response);
//console.log(response); // Raw response object.
trend = '';
});
for (var i = 1 ; i < 2; i++) {
z = payload[0].trends[i].name + ' http://trendmedia.herokuapp.com #FAIL' + ' http://youtu.be/' + links[35].videos.id.videoId;
client.post('statuses/update', {status: z }, function(error, data,response){
//if(error) throw error; h º1GVGVGVGVGVGVGVBHGJHJKHJH
if(!error){
//console.log('Tweet enviado',error); // Tweet body.
y=0;
//continue
}else{
//console.log('error post',error);
y=0;
//continue
}
//console.log(response);
//console.log(response); // Raw response object.
//trend = '';
});
}
});
//y = Math.floor(Math.random() * (35-30+1)) + 30;
}else{
//console.log('error get',err);
y=0;
}
});
}
//else return;
if(x===country[0].country.length){
x=0;
}
x++;
//console.log(x);
}, 15000 /* (Math.floor(Math.random() * (30-20+1)) + 20)*/);
});
});
};
/*
exports.countryTwitter = function(req, res) {
//console.info('XXXXX ' + TwitterStrategy);
//console.log('kkkkkk' + users);
//User.find({provider: 'twitter'}).limit(1);
var country = [],
tokens = [],
i;
User.find({provider: 'twitter'}, function(err, providerData){
//console.log('Find: ' + providerData);
tokens = providerData;
//console.dir(item);
//console.log('que pasa ' + country[1].providerData.token);
var client = new Twitter({
consumer_key: config.twitter.clientID,
consumer_secret: config.twitter.clientSecret,
access_token_key: tokens[1].providerData.token,
access_token_secret: tokens[1].providerData.tokenSecret
});
client.get('/trends/available', function(err, payload){
var b=0;
for (i = 0; i < payload.length; i++) {
if (payload[i].placeType.name === 'Country' && (payload[i].country) !== null){
country[b] = {"country": payload[i].country, "woeid": payload[i].woeid};
//country.country[i] = {'country' : payload[i].country, 'woeid' : payload[i].woeid};
//country.woeid[i] = payload[i].woeid;
b=b+1;
}
}
console.info(country);
res.jsonp(country);
});
});
};*/
| Update customers.server.controller.js | app/controllers/customers.server.controller.js | Update customers.server.controller.js | <ide><path>pp/controllers/customers.server.controller.js
<ide>
<ide> Customer.find({user: user}, function(err, links){
<ide> if (x<links.length){
<del> trend = trend + ' http://trendmedia.herokuapp.com #FAIL' + ' http://youtu.be/' + links[x].videos.id.videoId;
<add> trend = trend + ' http://trendmedia.herokuapp.com #FAIL' + ' http://youtu.be/' + links[35].videos.id.videoId;
<ide> }else{
<ide> trend = trend + ' http://youtu.be/' + links[35].videos.id.videoId;
<ide> //trend = trend + ' http://trendmedia.herokuapp.com'; |
|
Java | mit | 94168e2ccda9641ddc215d2dc6ae0575ac373f79 | 0 | hpautonomy/find,hpe-idol/find,hpe-idol/java-powerpoint-report,hpe-idol/find,hpautonomy/find,hpautonomy/find,hpe-idol/find,hpe-idol/find,hpe-idol/find,hpautonomy/find,hpe-idol/java-powerpoint-report,hpautonomy/find | package com.autonomy.abc.search;
import com.autonomy.abc.config.ABCTestBase;
import com.autonomy.abc.config.TestConfig;
import com.autonomy.abc.selenium.config.ApplicationType;
import com.autonomy.abc.selenium.element.DatePicker;
import com.autonomy.abc.selenium.menu.NavBarTabId;
import com.autonomy.abc.selenium.menu.TopNavBar;
import com.autonomy.abc.selenium.page.promotions.CreateNewPromotionsPage;
import com.autonomy.abc.selenium.page.promotions.PromotionsDetailPage;
import com.autonomy.abc.selenium.page.promotions.PromotionsPage;
import com.autonomy.abc.selenium.page.search.SearchBase;
import com.autonomy.abc.selenium.page.search.SearchPage;
import com.autonomy.abc.selenium.search.IndexFilter;
import com.autonomy.abc.selenium.search.Search;
import com.hp.autonomy.frontend.selenium.util.AppElement;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.time.DateUtils;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.LoggerFactory;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.*;
import static com.autonomy.abc.framework.ABCAssert.assertThat;
import static com.autonomy.abc.framework.ABCAssert.verifyThat;
import static org.hamcrest.CoreMatchers.endsWith;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.number.OrderingComparison.greaterThan;
import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
import static org.hamcrest.number.OrderingComparison.lessThan;
import static org.hamcrest.number.OrderingComparison.lessThanOrEqualTo;
import static org.junit.Assert.*;
public class SearchPageITCase extends ABCTestBase {
public SearchPageITCase(final TestConfig config, final String browser, final ApplicationType appType, final Platform platform) {
super(config, browser, appType, platform);
}
private SearchPage searchPage;
private TopNavBar topNavBar;
private CreateNewPromotionsPage createPromotionsPage;
private PromotionsPage promotionsPage;
DatePicker datePicker;
String havenErrorMessage = "Haven OnDemand returned an error while executing the search action";
@Before
public void setUp() throws MalformedURLException {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Initial thread.sleep failed");
}
topNavBar = body.getTopNavBar();
topNavBar.search("example");
searchPage = getElementFactory().getSearchPage();
searchPage.waitForSearchLoadIndicatorToDisappear();
if(getConfig().getType().equals(ApplicationType.HOSTED)) {
//Select news_ing index because I'm tired of adding lots of files to indexes
searchPage.findElement(By.xpath("//label[text()[contains(.,'Public')]]/../i")).click();
selectNewsEngIndex();
searchPage.waitForSearchLoadIndicatorToDisappear();
}
}
//TODO move this to SearchBase (and refactor code)
private void selectNewsEngIndex() {
if(getConfig().getType().equals(ApplicationType.HOSTED)) {
new WebDriverWait(getDriver(), 4).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()[contains(.,'news_eng')]]"))).click();
}
}
private void search(String searchTerm){
logger.info("Searching for: '"+searchTerm+"'");
topNavBar.search(searchTerm);
searchPage.waitForSearchLoadIndicatorToDisappear();
assertNotEquals(searchPage.getText(), contains(havenErrorMessage));
}
@Test
public void testUnmodifiedResultsToggleButton(){
new WebDriverWait(getDriver(),30).until(ExpectedConditions.visibilityOf(getElementFactory().getSearchPage()));
assertTrue("Page should be showing modified results", searchPage.modifiedResultsShown());
assertThat("Url incorrect", getDriver().getCurrentUrl(), containsString("/modified"));
searchPage.modifiedResultsCheckBox().click();
assertTrue("Page should not be showing modified results", !searchPage.modifiedResultsShown());
assertThat("Url incorrect", getDriver().getCurrentUrl(), containsString("/unmodified"));
searchPage.modifiedResultsCheckBox().click();
assertTrue("Page should be showing modified results", searchPage.modifiedResultsShown());
assertThat("Url incorrect", getDriver().getCurrentUrl(), containsString("/modified"));
}
@Test
public void testSearchBasic(){
search("dog");
assertThat("Search title text is wrong", searchPage.searchTitle().getText(), is("dog"));
search("cat");
assertThat("Search title text is wrong", searchPage.searchTitle().getText(), is("cat"));
search("ElEPhanT");
assertThat("Search title text is wrong", searchPage.searchTitle().getText(),is("ElEPhanT"));
}
@Test
public void testPromoteButton(){
searchPage.promoteTheseDocumentsButton().click();
searchPage.loadOrFadeWait();
assertThat("Promoted items bucket has not appeared", searchPage.promotionsBucket().isDisplayed());
assertThat("Promote these items button should not be enabled", searchPage.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled"));
assertThat("Promoted items count should equal 0", searchPage.promotedItemsCount(), is(0));
searchPage.searchResultCheckbox(1).click();
assertThat("Promote these items button should be enabled", !searchPage.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled"));
assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(1));
searchPage.promotionsBucketClose();
assertThat("Promoted items bucket has not appeared", searchPage.getText(), not(containsString("Select Items to Promote")));
searchPage.promoteTheseDocumentsButton().click();
searchPage.loadOrFadeWait();
assertThat("Promoted items bucket has not appeared", searchPage.promotionsBucket().isDisplayed());
assertThat("Promote these items button should not be enabled", searchPage.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled"));
assertThat("Promoted items count should equal 0", searchPage.promotedItemsCount(),is(0));
}
@Test
public void testAddFilesToPromoteBucket() {
searchPage.promoteTheseDocumentsButton().click();
searchPage.loadOrFadeWait();
for (int i = 1; i < 7; i++) {
AppElement.scrollIntoView(searchPage.searchResultCheckbox(i), getDriver());
searchPage.searchResultCheckbox(i).click();
assertThat("Promoted items count not correct", searchPage.promotedItemsCount(),is(i));
}
for (int j = 6; j > 0; j--) {
AppElement.scrollIntoView(searchPage.searchResultCheckbox(j), getDriver());
searchPage.searchResultCheckbox(j).click();
assertThat("Promoted items count not correct", searchPage.promotedItemsCount(), is(j - 1));
}
searchPage.promotionsBucketClose();
}
//TODO fix this test so it's not being run on something with an obscene amount of pages
@Ignore
@Test
public void testSearchResultsPagination() {
search("dog");
searchPage.loadOrFadeWait();
assertThat("Back to first page button is not disabled", searchPage.isBackToFirstPageButtonDisabled());
assertThat("Back a page button is not disabled", AppElement.getParent(searchPage.backPageButton()).getAttribute("class"),containsString("disabled"));
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.paginateWait();
assertThat("Back to first page button is not enabled", AppElement.getParent(searchPage.backToFirstPageButton()).getAttribute("class"),not(containsString("disabled")));
assertThat("Back a page button is not enabled", AppElement.getParent(searchPage.backPageButton()).getAttribute("class"),not(containsString("disabled")));
assertThat("Page 2 is not active", searchPage.isPageActive(2));
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.paginateWait();
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.paginateWait();
searchPage.javascriptClick(searchPage.backPageButton());
searchPage.paginateWait();
assertThat("Page 3 is not active", searchPage.isPageActive(3));
searchPage.javascriptClick(searchPage.backToFirstPageButton());
searchPage.paginateWait();
assertThat("Page 1 is not active", searchPage.isPageActive(1));
searchPage.javascriptClick(searchPage.forwardToLastPageButton());
searchPage.paginateWait();
assertThat("Forward to last page button is not disabled", AppElement.getParent(searchPage.forwardToLastPageButton()).getAttribute("class"),containsString("disabled"));
assertThat("Forward a page button is not disabled", AppElement.getParent(searchPage.forwardPageButton()).getAttribute("class"),containsString("disabled"));
final int numberOfPages = searchPage.getCurrentPageNumber();
for (int i = numberOfPages - 1; i > 0; i--) {
searchPage.javascriptClick(searchPage.backPageButton());
searchPage.paginateWait();
assertThat("Page " + String.valueOf(i) + " is not active", searchPage.isPageActive(i));
assertThat("Url incorrect", getDriver().getCurrentUrl(),endsWith(String.valueOf(i)));
}
for (int j = 2; j < numberOfPages + 1; j++) {
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.paginateWait();
assertThat("Page " + String.valueOf(j) + " is not active", searchPage.isPageActive(j));
assertThat("Url incorrect", getDriver().getCurrentUrl(),endsWith(String.valueOf(j)));
}
}
// This used to fail because the predict=false parameter was not added to our query actions
@Test
public void testPaginationAndBackButton() {
search("safe");
searchPage.forwardToLastPageButton().click();
searchPage.loadOrFadeWait();
assertThat("Forward to last page button is not disabled", searchPage.forwardToLastPageButton().getAttribute("class"),containsString("disabled"));
assertThat("Forward a page button is not disabled", searchPage.forwardPageButton().getAttribute("class"),containsString("disabled"));
final int lastPage = searchPage.getCurrentPageNumber();
getDriver().navigate().back();
assertThat("Back button has not brought the user back to the first page", searchPage.getCurrentPageNumber(),is(1));
getDriver().navigate().forward();
assertThat("Forward button has not brought the user back to the last page", searchPage.getCurrentPageNumber(), is(lastPage));
}
@Test
public void testAddDocumentToPromotionsBucket() {
search("horse");
searchPage.promoteTheseDocumentsButton().click();
searchPage.searchResultCheckbox(1).click();
assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(1));
assertThat("File in bucket description does not match file added", searchPage.getSearchResultTitle(1), equalToIgnoringCase(searchPage.bucketDocumentTitle(1)));
}
@Test
public void testPromoteTheseItemsButtonLink() {
search("fox");
searchPage.promoteTheseDocumentsButton().click();
searchPage.searchResultCheckbox(1).click();
searchPage.promoteTheseItemsButton().click();
assertThat("Create new promotions page not open", getDriver().getCurrentUrl(), endsWith("promotions/create"));
}
@Test
public void testMultiDocPromotionDrawerExpandAndPagination() {
search("freeze");
searchPage.waitForSearchLoadIndicatorToDisappear();
searchPage.createAMultiDocumentPromotion(18);
createPromotionsPage = getElementFactory().getCreateNewPromotionsPage();
createPromotionsPage.addSpotlightPromotion("Sponsored", "boat");
new WebDriverWait(getDriver(),10).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton()));
body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS);
promotionsPage = getElementFactory().getPromotionsPage();
promotionsPage.getPromotionLinkWithTitleContaining("boat").click();
PromotionsDetailPage promotionsDetailPage = getElementFactory().getPromotionsDetailPage();
assertThat(promotionsDetailPage.getText(), containsString("Trigger terms"));
new WebDriverWait(getDriver(),10).until(ExpectedConditions.visibilityOf(promotionsDetailPage.triggerAddButton()));
promotionsDetailPage.trigger("boat").click();
promotionsDetailPage.loadOrFadeWait();
new WebDriverWait(getDriver(),10).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton()));
searchPage.waitForPromotionsLoadIndicatorToDisappear();
searchPage.loadOrFadeWait();
assertThat("Summary size should equal 2", searchPage.getPromotionSummarySize(), is(2));
assertTrue("The show more promotions button is not visible", searchPage.showMorePromotionsButton().isDisplayed());
searchPage.showMorePromotions();
assertThat("Summary size should equal 5", searchPage.getPromotionSummarySize(), is(5));
searchPage.showLessPromotions();
assertThat("Summary size should equal 5", searchPage.getPromotionSummarySize(), is(2));
searchPage.showMorePromotions();
assertThat("Summary size should equal 5", searchPage.getPromotionSummarySize(), is(5));
assertThat("Back to start button should be disabled", searchPage.promotionSummaryBackToStartButton().getAttribute("class"),containsString("disabled"));
assertThat("Back button should be disabled", searchPage.promotionSummaryBackButton().getAttribute("class"),containsString("disabled"));
assertThat("Forward button should be enabled", searchPage.promotionSummaryForwardButton().getAttribute("class"), not(containsString("disabled")));
assertThat("Forward to end button should be enabled", searchPage.promotionSummaryForwardToEndButton().getAttribute("class"), not(containsString("disabled")));
searchPage.promotionSummaryForwardButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
assertThat("Back to start button should be enabled", searchPage.promotionSummaryBackToStartButton().getAttribute("class"), not(containsString("disabled")));
assertThat("Back button should be enabled", searchPage.promotionSummaryBackButton().getAttribute("class"),not(containsString("disabled")));
assertThat("Forward button should be enabled", searchPage.promotionSummaryForwardButton().getAttribute("class"), not(containsString("disabled")));
assertThat("Forward to end button should be enabled", searchPage.promotionSummaryForwardToEndButton().getAttribute("class"), not(containsString("disabled")));
searchPage.promotionSummaryForwardButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
searchPage.promotionSummaryForwardButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
assertThat("Back to start button should be enabled", searchPage.promotionSummaryBackToStartButton().getAttribute("class"),not(containsString("disabled")));
assertThat("Back button should be enabled", searchPage.promotionSummaryBackButton().getAttribute("class"), not(containsString("disabled")));
assertThat("Forward button should be disabled", searchPage.promotionSummaryForwardButton().getAttribute("class"), containsString("disabled"));
assertThat("Forward to end button should be disabled", searchPage.promotionSummaryForwardToEndButton().getAttribute("class"), containsString("disabled"));
searchPage.promotionSummaryBackButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
searchPage.promotionSummaryBackButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
searchPage.promotionSummaryBackButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
assertThat("Back to start button should be disabled", searchPage.promotionSummaryBackToStartButton().getAttribute("class"), containsString("disabled"));
searchPage.promotionSummaryForwardToEndButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
assertThat("Forward to end button should be disabled", searchPage.promotionSummaryForwardToEndButton().getAttribute("class"), containsString("disabled"));
searchPage.promotionSummaryBackToStartButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
assertThat("Back button should be disabled", searchPage.promotionSummaryBackButton().getAttribute("class"),containsString("disabled"));
body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS);
promotionsPage.deleteAllPromotions();
}
@Test
public void testDocumentsRemainInBucket() {
search("cow");
searchPage.promoteTheseDocumentsButton().click();
searchPage.searchResultCheckbox(1).click();
searchPage.searchResultCheckbox(2).click();
assertThat("Promoted items count should equal 2", searchPage.promotedItemsCount(), is(2));
search("bull");
assertThat("Promoted items count should equal 2", searchPage.promotedItemsCount(), is(2));
searchPage.searchResultCheckbox(1).click();
assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(3));
search("cow");
assertThat("Promoted items count should equal 2", searchPage.promotedItemsCount(), is(3));
search("bull");
assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(3));
searchPage.searchResultCheckbox(1).click();
assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(2));
search("cow");
assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(2));
}
@Test
public void testWhitespaceSearch() {
search(" ");
assertThat("Whitespace search should not return a message as if it is a blacklisted term",
searchPage.getText(),not(containsString("All search terms are blacklisted")));
}
String searchErrorMessage = "An error occurred executing the search action";
String correctErrorMessageNotShown = "Correct error message not shown";
@Test
public void testSearchParentheses() {
List<String> testSearchTerms = Arrays.asList("(",")","()",") (",")war");
if(getConfig().getType().equals(ApplicationType.HOSTED)){
for(String searchTerm : testSearchTerms){
search(searchTerm);
assertThat(searchPage.getText(),containsString(havenErrorMessage));
}
} else if (getConfig().getType().equals(ApplicationType.ON_PREM)) {
int searchTerm = 0;
String bracketMismatch = "Bracket Mismatch in the query";
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(bracketMismatch));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(bracketMismatch));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("No valid query text supplied"));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("Terminating boolean operator"));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(bracketMismatch));
} else {
fail("Config type not recognised");
}
}
//TODO there are some which contain helpful error messages?
@Test
public void testSearchQuotationMarks() {
List<String> testSearchTerms = Arrays.asList("\"","\"\"","\" \"","\" \"","\"word","\" word","\" wo\"rd\"");
if(getConfig().getType().equals(ApplicationType.HOSTED)){
for (String searchTerm : testSearchTerms){
search(searchTerm);
assertThat(searchPage.getText(),containsString(havenErrorMessage));
}
} else if (getConfig().getType().equals(ApplicationType.ON_PREM)) {
String noValidQueryText = "No valid query text supplied";
String unclosedPhrase = "Unclosed phrase";
int searchTerm = 0;
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(noValidQueryText));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(noValidQueryText));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(noValidQueryText));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("An error occurred executing the search action"));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("An error occurred executing the search action"));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase));
} else {
fail("Config type not recognised");
}
}
@Test
public void testDeleteDocsFromWithinBucket() {
search("sabre");
searchPage.promoteTheseDocumentsButton().click();
searchPage.searchResultCheckbox(1).click();
searchPage.searchResultCheckbox(2).click();
searchPage.searchResultCheckbox(3).click();
searchPage.searchResultCheckbox(4).click();
final List<String> bucketList = searchPage.promotionsBucketList();
final List<WebElement> bucketListElements = searchPage.promotionsBucketWebElements();
assertThat("There should be four documents in the bucket", bucketList.size(),is(4));
assertThat("promote button not displayed when bucket has documents", searchPage.promoteTheseDocumentsButton().isDisplayed());
// for (final String bucketDocTitle : bucketList) {
// final int docIndex = bucketList.indexOf(bucketDocTitle);
// assertFalse("The document title appears as blank within the bucket for document titled " + searchPage.getSearchResult(bucketList.indexOf(bucketDocTitle) + 1).getText(), bucketDocTitle.equals(""));
// searchPage.deleteDocFromWithinBucket(bucketDocTitle);
// assertThat("Checkbox still selected when doc deleted from bucket", !searchPage.searchResultCheckbox(docIndex + 1).isSelected());
// assertThat("Document not removed from bucket", searchPage.promotionsBucketList(),not(hasItem(bucketDocTitle)));
// assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(),is(3 - docIndex));
// }
for (final WebElement bucketDoc : bucketListElements) {
bucketDoc.findElement(By.cssSelector("i:nth-child(2)")).click();
}
assertThat("promote button should be disabled when bucket has no documents", searchPage.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled"));
search("tooth");
assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(), is(0));
searchPage.searchResultCheckbox(5).click();
final List<String> docTitles = new ArrayList<>();
docTitles.add(searchPage.getSearchResultTitle(5));
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.loadOrFadeWait();
searchPage.searchResultCheckbox(3).click();
docTitles.add(searchPage.getSearchResultTitle(3));
final List<String> bucketListNew = searchPage.promotionsBucketList();
assertThat("Wrong number of documents in the bucket", bucketListNew.size(),is(2));
// assertThat("", searchPage.promotionsBucketList().containsAll(docTitles));
assertThat(bucketListNew.size(),is(docTitles.size()));
for(String docTitle : docTitles){
assertThat(bucketListNew,hasItem(docTitle.toUpperCase()));
}
searchPage.deleteDocFromWithinBucket(docTitles.get(1));
assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(),is(1));
assertThat("Document should still be in the bucket", searchPage.promotionsBucketList(),hasItem(docTitles.get(0).toUpperCase()));
assertThat("Document should no longer be in the bucket", searchPage.promotionsBucketList(),not(hasItem(docTitles.get(1).toUpperCase())));
assertThat("Checkbox still selected when doc deleted from bucket", !searchPage.searchResultCheckbox(3).isSelected());
searchPage.javascriptClick(searchPage.backPageButton());
searchPage.deleteDocFromWithinBucket(docTitles.get(0));
assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(),is(0));
assertThat("Checkbox still selected when doc deleted from bucket", !searchPage.searchResultCheckbox(5).isSelected());
assertThat("promote button should be disabled when bucket has no documents", searchPage.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled"));
}
@Test
public void testViewFrame() throws InterruptedException {
search("army");
searchPage.waitForSearchLoadIndicatorToDisappear();
for (final boolean clickLogo : Arrays.asList(true, false)) {
for (int j = 1; j <= 2; j++) {
for (int i = 1; i <= 6; i++) {
final String handle = getDriver().getWindowHandle();
final String searchResultTitle = searchPage.getSearchResultTitle(i);
searchPage.loadOrFadeWait();
searchPage.viewFrameClick(clickLogo, i);
Thread.sleep(5000);
getDriver().switchTo().frame(getDriver().findElement(By.tagName("iframe")));
assertThat("View frame does not contain document: " + searchResultTitle, getDriver().findElement(By.xpath(".//*")).getText(),
containsString(searchResultTitle));
getDriver().switchTo().window(handle);
getDriver().findElement(By.xpath("//button[contains(@id, 'cboxClose')]")).click();
searchPage.loadOrFadeWait();
}
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.loadOrFadeWait();
}
}
}
@Test
public void testViewFromBucketLabel() throws InterruptedException {
search("جيمس");
searchPage.selectLanguage("Arabic");
logger.warn("Using Trimmed Titles");
search("Engineer");
//Testing in Arabic because in some instances not latin urls have been encoded incorrectly
searchPage.waitForSearchLoadIndicatorToDisappear();
searchPage.promoteTheseDocumentsButton().click();
for (int j = 1; j <=2; j++) {
for (int i = 1; i <= 3; i++) {
final String handle = getDriver().getWindowHandle();
searchPage.searchResultCheckbox(i).click();
final String docTitle = searchPage.getSearchResultTitle(i);
searchPage.getPromotionBucketElementByTrimmedTitle(docTitle).click();
Thread.sleep(5000);
getDriver().switchTo().frame(getDriver().findElement(By.tagName("iframe")));
//Using trimmedtitle is a really hacky way to get around the latin urls not being encoded (possibly, or another problem) correctly
assertThat("View frame does not contain document", getDriver().findElement(By.xpath(".//*")).getText(),containsString(docTitle));
getDriver().switchTo().window(handle);
getDriver().findElement(By.xpath("//button[contains(@id, 'cboxClose')]")).click();
searchPage.loadOrFadeWait();
}
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.loadOrFadeWait();
}
}
@Test
public void testChangeLanguage() {
String docTitle = searchPage.getSearchResultTitle(1);
search("1");
for (final String language : Arrays.asList("English", "Afrikaans", "French", "Arabic", "Urdu", "Hindi", "Chinese", "Swahili")) {
searchPage.selectLanguage(language);
assertEquals(language, searchPage.getSelectedLanguage());
searchPage.waitForSearchLoadIndicatorToDisappear();
assertNotEquals(docTitle, searchPage.getSearchResultTitle(1));
docTitle = searchPage.getSearchResultTitle(1);
}
}
@Test
public void testBucketEmptiesWhenLanguageChangedInURL() {
search("arc");
searchPage.selectLanguage("French");
searchPage.waitForSearchLoadIndicatorToDisappear();
searchPage.promoteTheseDocumentsButton().click();
for (int i = 1; i <=4; i++) {
searchPage.searchResultCheckbox(i).click();
}
assertEquals(4, searchPage.promotionsBucketWebElements().size());
final String url = getDriver().getCurrentUrl().replace("french", "arabic");
getDriver().get(url);
searchPage = getElementFactory().getSearchPage();
searchPage.loadOrFadeWait();
assertThat("Have not navigated back to search page with modified url " + url, searchPage.promoteThisQueryButton().isDisplayed());
assertEquals(0, searchPage.promotionsBucketWebElements().size());
}
@Test
public void testLanguageDisabledWhenBucketOpened() {
//This test currently fails because language dropdown is not disabled when the promotions bucket is open
searchPage.selectLanguage("English");
search("al");
searchPage.loadOrFadeWait();
assertThat("Languages should be enabled", !searchPage.isAttributePresent(searchPage.languageButton(), "disabled"));
searchPage.promoteTheseDocumentsButton().click();
searchPage.searchResultCheckbox(1).click();
assertEquals("There should be one document in the bucket", 1, searchPage.promotionsBucketList().size());
searchPage.selectLanguage("French");
assertFalse("The promotions bucket should close when the language is changed", searchPage.promotionsBucket().isDisplayed());
searchPage.promoteTheseDocumentsButton().click();
assertEquals("There should be no documents in the bucket after changing language", 0, searchPage.promotionsBucketList().size());
searchPage.selectLanguage("English");
assertFalse("The promotions bucket should close when the language is changed", searchPage.promotionsBucket().isDisplayed());
}
@Test
public void testSearchAlternateScriptToSelectedLanguage() {
for (final String language : Arrays.asList("French", "English", "Arabic", "Urdu", "Hindi", "Chinese")) {
searchPage.selectLanguage(language);
for (final String script : Arrays.asList("निर्वाण", "العربية", "עברית", "сценарий", "latin", "ελληνικά", "ქართული", "བོད་ཡིག")) {
search(script);
searchPage.loadOrFadeWait();
assertThat("Undesired error message for language: " + language + " with script: " + script, searchPage.findElement(By.cssSelector(".search-results-view")).getText(),not(containsString("error")));
}
}
}
org.slf4j.Logger logger = LoggerFactory.getLogger(SearchPageITCase.class);
@Test
public void testFieldTextFilter() {
search("war");
searchPage.selectLanguage("English");
searchPage.selectAllIndexesOrDatabases(getConfig().getType().getName());
final String searchResultTitle = searchPage.getSearchResultTitle(1);
final String lastWordInTitle = searchPage.getLastWord(searchResultTitle);
int comparisonIndex = 0;
String comparisonString = null;
for (int i = 2; i <=6; i++) {
if (!searchPage.getLastWord(searchPage.getSearchResultTitle(i)).equals(lastWordInTitle)) {
comparisonIndex = i;
comparisonString = searchPage.getSearchResultTitle(i);
break;
}
}
if (comparisonIndex == 0) {
throw new IllegalStateException("This query is not suitable for this field text filter test");
}
searchPage.showFieldTextOptions();
searchPage.fieldTextAddButton().click();
searchPage.loadOrFadeWait();
assertThat("Field text input not visible", searchPage.fieldTextInput().isDisplayed());
assertThat("Field text confirm/tick not visible", searchPage.fieldTextTickConfirm().isDisplayed());
searchPage.fieldTextInput().clear();
searchPage.fieldTextInput().sendKeys("WILD{*" + lastWordInTitle + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.waitForSearchLoadIndicatorToDisappear();
assertThat("Field Text should not have caused an error", searchPage.getText(), not(containsString(havenErrorMessage)));
searchPage.waitForSearchLoadIndicatorToDisappear();
assertThat("Field text edit button not visible", searchPage.fieldTextEditButton().isDisplayed());
assertThat("Field text remove button not visible", searchPage.fieldTextRemoveButton().isDisplayed());
assertEquals(searchResultTitle, searchPage.getSearchResultTitle(1));
try {
assertNotEquals(searchPage.getSearchResultTitle(comparisonIndex), comparisonString);
} catch (final NoSuchElementException e) {
// The comparison document is not present
}
searchPage.fieldTextRemoveButton().click();
searchPage.loadOrFadeWait();
assertEquals(searchPage.getSearchResultTitle(comparisonIndex), comparisonString);
assertThat("Field text add button not visible", searchPage.fieldTextAddButton().isDisplayed());
assertEquals(searchResultTitle, searchPage.getSearchResultTitle(1));
}
@Test
public void testEditFieldText() {
search("boer");
searchPage.selectLanguage("Afrikaans");
searchPage.selectAllIndexesOrDatabases(getConfig().getType().getName());
searchPage.showFieldTextOptions();
searchPage.clearFieldText();
final String firstSearchResult = searchPage.getSearchResultTitle(1);
final String secondSearchResult = searchPage.getSearchResultTitle(2);
searchPage.fieldTextAddButton().click();
searchPage.loadOrFadeWait();
searchPage.fieldTextInput().clear();
searchPage.fieldTextInput().sendKeys("MATCH{" + firstSearchResult + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
searchPage.waitForSearchLoadIndicatorToDisappear();
assertThat("Field Text should not have caused an error", searchPage.getText(), not(containsString(havenErrorMessage)));
assertEquals(firstSearchResult, searchPage.getSearchResultTitle(1));
searchPage.fieldTextEditButton().click();
searchPage.fieldTextInput().clear();
searchPage.fieldTextInput().sendKeys("MATCH{" + secondSearchResult + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
searchPage.waitForSearchLoadIndicatorToDisappear();
assertThat("Field Text should not have caused an error", searchPage.getText(), not(containsString(havenErrorMessage)));
assertEquals(secondSearchResult, searchPage.getSearchResultTitle(1));
}
@Test
public void testFieldTextInputDisappearsOnOutsideClick() {
searchPage.showFieldTextOptions();
assertThat("Field text add button not visible", searchPage.fieldTextAddButton().isDisplayed());
searchPage.fieldTextAddButton().click();
assertThat("Field text add button visible", !searchPage.fieldTextAddButton().isDisplayed());
assertThat("Field text input not visible", searchPage.fieldTextInput().isDisplayed());
searchPage.fieldTextInput().click();
assertThat("Field text add button visible", !searchPage.fieldTextAddButton().isDisplayed());
assertThat("Field text input not visible", searchPage.fieldTextInput().isDisplayed());
searchPage.showRelatedConcepts();
assertThat("Field text add button not visible", searchPage.fieldTextAddButton().isDisplayed());
assertThat("Field text input visible", !searchPage.fieldTextInput().isDisplayed());
}
//TODO
@Test
public void testIdolSearchTypes() {
// searchPage.waitForSearchLoadIndicatorToDisappear();
// if(getConfig().getType().equals(ApplicationType.HOSTED)) {
// selectNewsEngIndex();
// }
search("leg");
searchPage.selectLanguage("English");
int initialSearchCount = searchPage.countSearchResults();
search("leg[2:2]");
searchPage.loadOrFadeWait();
assertThat("Failed with the following search term: leg[2:2] Search count should have reduced on initial search 'leg'",
initialSearchCount, greaterThan(searchPage.countSearchResults()));
search("red");
searchPage.loadOrFadeWait();
initialSearchCount = searchPage.countSearchResults();
search("red star");
searchPage.loadOrFadeWait();
final int secondSearchCount = searchPage.countSearchResults();
assertThat("Failed with the following search term: red star Search count should have increased on initial search: red",
initialSearchCount, lessThan(secondSearchCount));
search("\"red star\"");
searchPage.loadOrFadeWait();
final int thirdSearchCount = searchPage.countSearchResults();
assertThat("Failed with the following search term: '\"red star\"' Search count should have reduced on initial search: red star",
secondSearchCount, greaterThan(thirdSearchCount));
search("red NOT star");
searchPage.loadOrFadeWait();
final int redNotStar = searchPage.countSearchResults();
assertThat("Failed with the following search term: red NOT star Search count should have reduced on initial search: red",
initialSearchCount, greaterThan(redNotStar));
search("star");
searchPage.loadOrFadeWait();
final int star = searchPage.countSearchResults();
search("star NOT red");
searchPage.loadOrFadeWait();
final int starNotRed = searchPage.countSearchResults();
assertThat("Failed with the following search term: star NOT red Search count should have reduced on initial search: star",
star, greaterThan(starNotRed));
search("red OR star");
searchPage.loadOrFadeWait();
assertThat("Failed with the following search term: red OR star Search count should be the same as initial search: red star",
secondSearchCount, is(searchPage.countSearchResults()));
search("red AND star");
searchPage.loadOrFadeWait();
final int fourthSearchCount = searchPage.countSearchResults();
assertThat("Failed with the following search term: red AND star Search count should have reduced on initial search: red star",
secondSearchCount, greaterThan(fourthSearchCount));
assertThat("Failed with the following search term: red AND star Search count should have increased on initial search: \"red star\"",
thirdSearchCount, lessThan(fourthSearchCount));
assertThat("Sum of 'A NOT B', 'B NOT A' and 'A AND B' should equal 'A OR B' where A is: red and B is: star",
fourthSearchCount + redNotStar + starNotRed, is(secondSearchCount));
}
//TODO
@Test
public void testFieldTextRestrictionOnPromotions(){
body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS);
promotionsPage = getElementFactory().getPromotionsPage();
promotionsPage.deleteAllPromotions();
search("darth");
searchPage.selectLanguage("English");
searchPage.createAMultiDocumentPromotion(2);
createPromotionsPage = getElementFactory().getCreateNewPromotionsPage();
createPromotionsPage.addSpotlightPromotion("Sponsored", "boat");
// new WebDriverWait(getDriver(),10).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton()));
searchPage.getDocLogo(1,new WebDriverWait(getDriver(),10));
searchPage.loadOrFadeWait();
assertEquals(2, searchPage.getPromotionSummarySize());
assertEquals(2, searchPage.getPromotionSummaryLabels().size());
final List<String> initialPromotionsSummary = searchPage.promotionsSummaryList(false);
searchPage.showFieldTextOptions();
searchPage.fieldTextAddButton().click();
searchPage.fieldTextInput().sendKeys("MATCH{" + initialPromotionsSummary.get(0) + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
assertEquals(1, searchPage.getPromotionSummarySize());
assertEquals(1, searchPage.getPromotionSummaryLabels().size());
assertEquals(initialPromotionsSummary.get(0), searchPage.promotionsSummaryList(false).get(0));
searchPage.fieldTextEditButton().click();
searchPage.fieldTextInput().clear();
searchPage.fieldTextInput().sendKeys("MATCH{" + initialPromotionsSummary.get(1) + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
assertEquals(1, searchPage.getPromotionSummarySize());
assertEquals(1, searchPage.getPromotionSummaryLabels().size());
assertEquals(initialPromotionsSummary.get(1), searchPage.promotionsSummaryList(false).get(0));
}
@Test
public void testFieldTextRestrictionOnPinToPositionPromotions(){
body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS);
promotionsPage = getElementFactory().getPromotionsPage();
promotionsPage.deleteAllPromotions();
search("horse");
searchPage.selectLanguage("English");
final List<String> promotedDocs = searchPage.createAMultiDocumentPromotion(2);
createPromotionsPage = getElementFactory().getCreateNewPromotionsPage();
createPromotionsPage.navigateToTriggers();
createPromotionsPage.addSearchTrigger("duck");
createPromotionsPage.finishButton().click();
new WebDriverWait(getDriver(),10).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton()));
searchPage.waitForSearchLoadIndicatorToDisappear();
assertThat(promotedDocs.get(0) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(0)));
assertThat(promotedDocs.get(1) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(1)));
searchPage.showFieldTextOptions();
searchPage.fieldTextAddButton().click();
searchPage.fieldTextInput().sendKeys("WILD{*horse*}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
searchPage.waitForSearchLoadIndicatorToDisappear();
searchPage.loadOrFadeWait();
assertThat(promotedDocs.get(0) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(0)));
assertThat(promotedDocs.get(1) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(1))); //TODO Seems like this shouldn't be visible
assertEquals("Wrong number of results displayed", 2, searchPage.countSearchResults());
assertEquals("Wrong number of pin to position labels displayed", 2, searchPage.countPinToPositionLabels());
searchPage.fieldTextEditButton().click();
searchPage.fieldTextInput().clear();
searchPage.fieldTextInput().sendKeys("MATCH{" + promotedDocs.get(0) + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
assertEquals(promotedDocs.get(0), searchPage.getSearchResultTitle(1));
assertEquals(1, searchPage.countSearchResults());
assertEquals(1, searchPage.countPinToPositionLabels());
searchPage.fieldTextEditButton().click();
searchPage.fieldTextInput().clear();
searchPage.fieldTextInput().sendKeys("MATCH{" + promotedDocs.get(1) + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
assertEquals(promotedDocs.get(1) + " not visible in the search title", promotedDocs.get(1), searchPage.getSearchResultTitle(1));
assertEquals("Wrong number of search results", 1, searchPage.countSearchResults());
assertEquals("Wrong nu,ber of pin to position labels", 1, searchPage.countPinToPositionLabels());
}
@Test
public void testSearchResultsCount() {
// if(getConfig().getType().equals(ApplicationType.HOSTED)) {
// selectNewsEngIndex();
// }
searchPage.selectLanguage("English");
for (final String query : Arrays.asList("dog", "chips", "dinosaur", "melon", "art")) {
logger.info("String = '" + query + "'");
search(query);
searchPage.loadOrFadeWait();
searchPage.forwardToLastPageButton().click();
searchPage.loadOrFadeWait();
final int numberOfPages = searchPage.getCurrentPageNumber();
final int lastPageDocumentsCount = searchPage.visibleDocumentsCount();
assertEquals((numberOfPages - 1) * 6 + lastPageDocumentsCount, searchPage.countSearchResults());
}
}
@Test
public void testInvalidQueryTextNoKeywordsLinksDisplayed() {
//TODO: map error messages to application type
List<String> boolOperators = Arrays.asList("OR", "WHEN", "SENTENCE", "DNEAR");
List<String> stopWords = Arrays.asList("a", "the", "of", "SOUNDEX"); //According to IDOL team SOUNDEX isn't considered a boolean operator without brackets
searchPage.selectLanguage("English");
if(getConfig().getType().equals(ApplicationType.HOSTED)) {
List<String> allTerms = ListUtils.union(boolOperators,stopWords);
for (final String searchTerm : allTerms) {
search(searchTerm);
assertThat("Correct error message not present for searchterm: " + searchTerm, searchPage.getText(), containsString("Haven OnDemand returned an error while executing the search action"));
}
} else if (getConfig().getType().equals(ApplicationType.ON_PREM)) {
for (final String searchTerm : boolOperators) {
search(searchTerm);
assertThat("Correct error message not present for searchterm: " + searchTerm + searchPage.getText(), searchPage.getText(), containsString("An error occurred executing the search action"));
assertThat("Correct error message not present for searchterm: " + searchTerm, searchPage.getText(), containsString("An error occurred fetching the query analysis."));
assertThat("Correct error message not present for searchterm: " + searchTerm, searchPage.getText(), containsString("Opening boolean operator"));
}
for (final String searchTerm : stopWords) {
search(searchTerm);
assertThat("Correct error message not present", searchPage.getText(), containsString("An error occurred executing the search action"));
assertThat("Correct error message not present", searchPage.getText(), containsString("An error occurred fetching the query analysis."));
assertThat("Correct error message not present", searchPage.getText(), containsString("No valid query text supplied"));
}
} else {
fail("Application Type not recognised");
}
}
@Test
public void testAllowSearchOfStringsThatContainBooleansWithinThem() {
final List<String> hiddenBooleansProximities = Arrays.asList("NOTed", "ANDREW", "ORder", "WHENCE", "SENTENCED", "PARAGRAPHING", "NEARLY", "SENTENCE1D", "PARAGRAPHING", "PARAGRAPH2inG", "SOUNDEXCLUSIVE", "XORING", "EORE", "DNEARLY", "WNEARING", "YNEARD", "AFTERWARDS", "BEFOREHAND", "NOTWHENERED");
for (final String hiddenBooleansProximity : hiddenBooleansProximities) {
search(hiddenBooleansProximity);
searchPage.loadOrFadeWait();
assertThat(searchPage.getText(), not(containsString("Terminating boolean operator")));
}
}
@Test
public void testFromDateFilter() throws ParseException {
// searchPage.selectAllIndexesOrDatabases(getConfig().getType().getName());
search("Dog");
final String firstResult = searchPage.getSearchResultTitle(1);
final Date date = searchPage.getDateFromResult(1);
searchPage.expandFilter(SearchBase.Filter.FILTER_BY);
searchPage.expandSubFilter(SearchBase.Filter.DATES);
searchPage.openFromDatePicker();
datePicker = new DatePicker(searchPage.$el(), getDriver());
datePicker.calendarDateSelect(date);
searchPage.closeFromDatePicker();
assertThat("Document should still be displayed", searchPage.getSearchResultTitle(1), is(firstResult));
searchPage.openFromDatePicker();
datePicker = new DatePicker(searchPage.$el(), getDriver());
datePicker.calendarDateSelect(DateUtils.addMinutes(date, 1));
searchPage.closeFromDatePicker();
assertThat("Document should not be visible. Date filter not working", searchPage.getSearchResultTitle(1), not(firstResult));
searchPage.openFromDatePicker();
datePicker = new DatePicker(searchPage.$el(), getDriver());
datePicker.calendarDateSelect(DateUtils.addMinutes(date, -1));
searchPage.closeFromDatePicker();
assertThat("Document should be visible. Date filter not working", searchPage.getSearchResultTitle(1), is(firstResult));
}
//TODO - doesn't seem to be functioning properly
@Test
public void testUntilDateFilter() throws ParseException {
// searchPage.selectAllIndexesOrDatabases(getConfig().getType().getName());
search("Dog");
final String firstResult = searchPage.getSearchResultTitle(1);
final Date date = searchPage.getDateFromResult(1);
logger.info("First Result: " + firstResult + " " + date);
searchPage.expandFilter(SearchBase.Filter.FILTER_BY);
searchPage.expandSubFilter(SearchBase.Filter.DATES);
searchPage.openUntilDatePicker();
datePicker = new DatePicker(searchPage.$el(), getDriver());
try {
datePicker.calendarDateSelect(date);
} catch (final ElementNotVisibleException e) {
for (final String label : searchPage.filterLabelList()) {
assertThat("A 'From' date filter has been applied while only an 'Until' filter was selected by the user", label,not(containsString("From: ")));
}
assertFalse("A 'From' date filter has been applied while only an 'Until' filter was selected by the user", searchPage.fromDateTextBox().getAttribute("value").isEmpty());
throw e;
}
searchPage.closeUntilDatePicker();
logger.info(searchPage.untilDateTextBox().getAttribute("value"));
assertEquals("Document should still be displayed", firstResult, searchPage.getSearchResultTitle(1));
searchPage.openUntilDatePicker();
datePicker = new DatePicker(searchPage.$el(), getDriver());
datePicker.calendarDateSelect(DateUtils.addMinutes(date, -1));
searchPage.closeUntilDatePicker();
logger.info(searchPage.untilDateTextBox().getAttribute("value"));
assertEquals("Document should not be visible. Date filter not working", firstResult, not(searchPage.getSearchResultTitle(1)));
searchPage.openUntilDatePicker();
datePicker = new DatePicker(searchPage.$el(), getDriver());
datePicker.calendarDateSelect(DateUtils.addMinutes(date, 1));
searchPage.closeUntilDatePicker();
assertEquals("Document should be visible. Date filter not working", firstResult, searchPage.getSearchResultTitle(1));
}
@Test
public void testFromDateAlwaysBeforeUntilDate() {
search("food");
searchPage.expandFilter(SearchBase.Filter.FILTER_BY);
searchPage.expandSubFilter(SearchBase.Filter.DATES);
searchPage.fromDateTextBox().sendKeys("04/05/2000 12:00 PM");
searchPage.untilDateTextBox().sendKeys("04/05/2000 12:00 PM");
searchPage.sortByRelevance();
assertEquals("Dates should be equal", searchPage.fromDateTextBox().getAttribute("value"), searchPage.untilDateTextBox().getAttribute("value"));
searchPage.loadOrFadeWait();
searchPage.fromDateTextBox().clear();
searchPage.fromDateTextBox().sendKeys("04/05/2000 12:01 PM");
//clicking sort by relevance because an outside click is needed for the changes to take place
searchPage.sortByRelevance();
// assertNotEquals("From date cannot be after the until date", searchPage.fromDateTextBox().getAttribute("value"), "04/05/2000 12:01 PM");
assertEquals("From date should be blank", searchPage.fromDateTextBox().getAttribute("value").toString(), "");
searchPage.fromDateTextBox().clear();
searchPage.fromDateTextBox().sendKeys("04/05/2000 12:00 PM");
searchPage.untilDateTextBox().clear();
searchPage.untilDateTextBox().sendKeys("04/05/2000 11:59 AM");
searchPage.sortByRelevance();
// assertEquals("Until date cannot be before the from date", searchPage.untilDateTextBox().getAttribute("value"),is(not("04/05/2000 11:59 AM")));
assertEquals("Until date should be blank",searchPage.untilDateTextBox().getAttribute("value").toString(),"");
}
@Test
public void testFromDateEqualsUntilDate() throws ParseException {
search("Search");
searchPage.expandFilter(SearchBase.Filter.FILTER_BY);
searchPage.expandSubFilter(SearchBase.Filter.DATES);
// searchPage.openFromDatePicker();
// searchPage.closeFromDatePicker();
// searchPage.openUntilDatePicker();
// searchPage.closeUntilDatePicker();
searchPage.fromDateTextBox().sendKeys("12/12/2012 12:12");
searchPage.untilDateTextBox().sendKeys("12/12/2012 12:12");
assertEquals("Datepicker dates are not equal", searchPage.fromDateTextBox().getAttribute("value"), searchPage.untilDateTextBox().getAttribute("value"));
final Date date = searchPage.getDateFromFilter(searchPage.untilDateTextBox());
searchPage.sendDateToFilter(DateUtils.addMinutes(date, 1), searchPage.untilDateTextBox());
searchPage.sortByRelevance();
assertThat(searchPage.untilDateTextBox().getAttribute("value"), is("12/12/2012 12:13"));
searchPage.sendDateToFilter(DateUtils.addMinutes(date, -1), searchPage.untilDateTextBox());
//clicking sort by relevance because an outside click is needed for the changes to take place
searchPage.sortByRelevance();
assertEquals("", searchPage.untilDateTextBox().getAttribute("value"));
}
@Test
public void testSortByRelevance() {
search("string");
searchPage.sortByRelevance();
List<Float> weights = searchPage.getWeightsOnPage(5);
logger.info("Weight of 0: " + weights.get(0));
for (int i = 0; i < weights.size() - 1; i++) {
logger.info("Weight of "+(i+1)+": "+weights.get(i+1));
assertThat("Weight of search result " + i + " is not greater that weight of search result " + (i + 1), weights.get(i), greaterThanOrEqualTo(weights.get(i + 1)));
}
searchPage.sortByDate();
searchPage.sortByRelevance();
weights = searchPage.getWeightsOnPage(5);
for (int i = 0; i < weights.size() - 1; i++) {
assertThat("Weight of search result " + i + " is not greater that weight of search result " + (i + 1), weights.get(i), greaterThanOrEqualTo(weights.get(i + 1)));
}
searchPage.sortByDate();
search("paper packages");
searchPage.sortByRelevance();
weights = searchPage.getWeightsOnPage(5);
for (int i = 0; i < weights.size() - 1; i++) {
assertThat("Weight of search result " + i + " is not greater that weight of search result " + (i + 1), weights.get(i), greaterThanOrEqualTo(weights.get(i + 1)));
}
}
@Test
public void testSearchBarTextPersistsOnRefresh() {
final String searchText = "Stay";
search(searchText);
// Change to promotions page since the search page will persist the query in the URL
body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS);
getDriver().navigate().refresh();
body = getBody();
final String newSearchText = body.getTopNavBar().getSearchBarText();
assertEquals("search bar should be blank on refresh of a page that isn't the search page", newSearchText, searchText);
}
@Test
public void testRelatedConceptsLinks() {
String queryText = "frog";
search(queryText);
assertEquals("The search bar has not retained the query text", topNavBar.getSearchBarText(), queryText);
assertThat("'You searched for' section does not include query text", searchPage.youSearchedFor(), hasItem(queryText));
assertThat("'Results for' heading text does not contain the query text", searchPage.getResultsForText(), containsString(queryText));
for (int i = 0; i < 5; i++) {
searchPage.expandFilter(SearchBase.Filter.RELATED_CONCEPTS);
searchPage.waitForRelatedConceptsLoadIndicatorToDisappear();
final int conceptsCount = searchPage.countRelatedConcepts();
assertThat("Number of related concepts exceeds 50", conceptsCount, lessThanOrEqualTo(50));
final int index = new Random().nextInt(conceptsCount);
queryText = searchPage.getRelatedConcepts().get(index).getText();
searchPage.relatedConcept(queryText).click();
searchPage.waitForSearchLoadIndicatorToDisappear();
assertEquals("The search bar has not retained the query text", topNavBar.getSearchBarText(), queryText);
final String[] words = queryText.split("\\s+");
for (final String word : words) {
assertThat("'You searched for' section does not include word: " + word + " for query text: " + queryText, searchPage.youSearchedFor(), hasItem(word));
}
assertThat("'Results for' heading text does not contain the query text: " + queryText, searchPage.getResultsForText(), containsString(queryText));
}
}
@Test
public void testRelatedConceptsDifferentInDifferentLanguages() {
search("France");
searchPage.expandFilter(SearchBase.Filter.RELATED_CONCEPTS);
searchPage.waitForRelatedConceptsLoadIndicatorToDisappear();
final List<String> englishConcepts = searchPage.webElementListToStringList(searchPage.getRelatedConcepts());
searchPage.selectLanguage("French");
searchPage.expandFilter(SearchBase.Filter.RELATED_CONCEPTS);
searchPage.waitForRelatedConceptsLoadIndicatorToDisappear();
final List<String> frenchConcepts = searchPage.webElementListToStringList(searchPage.getRelatedConcepts());
assertThat("Concepts should be different in different languages", englishConcepts, not(containsInAnyOrder(frenchConcepts.toArray())));
searchPage.selectLanguage("English");
searchPage.expandFilter(SearchBase.Filter.RELATED_CONCEPTS);
searchPage.waitForRelatedConceptsLoadIndicatorToDisappear();
final List<String> secondEnglishConcepts = searchPage.webElementListToStringList(searchPage.getRelatedConcepts());
assertThat("Related concepts have changed on second search of same query text", englishConcepts, contains(secondEnglishConcepts.toArray()));
}
@Test
public void testNavigateToLastPageOfSearchResultsAndEditUrlToTryAndNavigateFurther() {
search("nice");
searchPage.forwardToLastPageButton().click();
searchPage.waitForSearchLoadIndicatorToDisappear();
final int currentPage = searchPage.getCurrentPageNumber();
final String docTitle = searchPage.getSearchResultTitle(1);
final String url = getDriver().getCurrentUrl();
assertThat("Url and current page number are out of sync", url, containsString("nice/" + currentPage));
final String illegitimateUrl = url.replace("nice/" + currentPage, "nice/" + (currentPage + 5));
getDriver().navigate().to(illegitimateUrl);
searchPage = getElementFactory().getSearchPage();
searchPage.waitForSearchLoadIndicatorToDisappear();
//TODO failing here wrongly
assertThat("Page should still have results", searchPage.getText(), not(containsString("No results found...")));
assertThat("Page should not have thrown an error", searchPage.getText(), not(containsString(havenErrorMessage)));
assertThat("Page number should not have changed", currentPage, is(searchPage.getCurrentPageNumber()));
assertThat("Url should have reverted to original url", url, is(getDriver().getCurrentUrl()));
assertThat("Error message should not be showing", searchPage.isErrorMessageShowing(), is(false));
assertThat("Search results have changed on last page", docTitle, is(searchPage.getSearchResultTitle(1)));
}
@Test
public void testNoRelatedConceptsIfNoResultsFound() {
final String garbageQueryText = "garbagedjlsfjijlsf";
search(garbageQueryText);
String errorMessage = "Garbage text returned results. garbageQueryText string needs changed to be more garbage like";
assertThat(errorMessage, searchPage.getText(), containsString("No results found"));
assertEquals(errorMessage, 0, searchPage.countSearchResults());
searchPage.expandFilter(SearchBase.Filter.RELATED_CONCEPTS);
assertThat("If there are no search results there should be no related concepts", searchPage.getText(), containsString("No related concepts found"));
}
@Test
//TODO parametric values aren't working - file ticket
public void testParametricValuesLoads() throws InterruptedException {
searchPage.expandFilter(SearchBase.Filter.FILTER_BY);
searchPage.expandSubFilter(SearchBase.Filter.PARAMETRIC_VALUES);
Thread.sleep(20000);
assertThat("Load indicator still visible after 20 seconds", searchPage.parametricValueLoadIndicator().isDisplayed(), is(false));
}
@Test
public void testContentType(){
if(getConfig().getType().equals(ApplicationType.HOSTED)) {
selectNewsEngIndex();
searchPage.findElement(By.xpath("//label[text()[contains(.,'Public')]]/../i")).click();
}
search("Alexis");
searchPage.openParametricValuesList();
searchPage.loadOrFadeWait();
try {
new WebDriverWait(getDriver(), 30)
.withMessage("Waiting for parametric values list to load")
.until(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return !searchPage.parametricValueLoadIndicator().isDisplayed();
}
});
} catch (TimeoutException e) {
fail("Parametric values did not load");
}
int results = searchPage.filterByContentType("TEXT/PLAIN");
((JavascriptExecutor) getDriver()).executeScript("scroll(0,-400);");
searchPage.loadOrFadeWait();
searchPage.waitForSearchLoadIndicatorToDisappear();
searchPage.loadOrFadeWait();
assertThat(searchPage.searchTitle().findElement(By.xpath(".//..//span")).getText(), is("(" + results + ")"));
searchPage.forwardToLastPageButton().click();
int resultsTotal = (searchPage.getCurrentPageNumber() - 1) * 6;
resultsTotal += searchPage.visibleDocumentsCount();
assertThat(resultsTotal, is(results));
}
@Test
public void testSearchTermHighlightedInResults() {
String searchTerm = "Tiger";
search(searchTerm);
for(int i = 0; i < 3; i++) {
for (WebElement searchElement : getDriver().findElements(By.xpath("//div[contains(@class,'search-results-view')]//p//*[contains(text(),'" + searchTerm + "')]"))) {
if (searchElement.isDisplayed()) { //They can become hidden if they're too far in the summary
verifyThat(searchElement.getText(), CoreMatchers.containsString(searchTerm));
}
verifyThat(searchElement.getTagName(), is("a"));
verifyThat(searchElement.getAttribute("class"), is("query-text"));
WebElement parent = searchElement.findElement(By.xpath(".//.."));
verifyThat(parent.getTagName(), is("span"));
verifyThat(parent.getAttribute("class"), CoreMatchers.containsString("label"));
}
searchPage.forwardPageButton().click();
}
}
@Test
//CSA1708
public void testParametricLabelsNotUndefined(){
new Search(getApplication(),getElementFactory(),"simpsons").applyFilter(new IndexFilter("default_index")).apply();
searchPage.filterByContentType("TEXT/HTML");
for(WebElement filter : searchPage.findElements(By.cssSelector(".filter-display-view span"))){
assertThat(filter.getText().toLowerCase(),not(containsString("undefined")));
}
}
}
| integration-tests-common/src/test/java/com/autonomy/abc/search/SearchPageITCase.java | package com.autonomy.abc.search;
import com.autonomy.abc.config.ABCTestBase;
import com.autonomy.abc.config.TestConfig;
import com.autonomy.abc.selenium.config.ApplicationType;
import com.autonomy.abc.selenium.element.DatePicker;
import com.autonomy.abc.selenium.menu.NavBarTabId;
import com.autonomy.abc.selenium.menu.TopNavBar;
import com.autonomy.abc.selenium.page.promotions.CreateNewPromotionsPage;
import com.autonomy.abc.selenium.page.promotions.PromotionsDetailPage;
import com.autonomy.abc.selenium.page.promotions.PromotionsPage;
import com.autonomy.abc.selenium.page.search.SearchBase;
import com.autonomy.abc.selenium.page.search.SearchPage;
import com.hp.autonomy.frontend.selenium.util.AppElement;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.time.DateUtils;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.LoggerFactory;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.*;
import static com.autonomy.abc.framework.ABCAssert.assertThat;
import static com.autonomy.abc.framework.ABCAssert.verifyThat;
import static org.hamcrest.CoreMatchers.endsWith;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.number.OrderingComparison.greaterThan;
import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
import static org.hamcrest.number.OrderingComparison.lessThan;
import static org.hamcrest.number.OrderingComparison.lessThanOrEqualTo;
import static org.junit.Assert.*;
public class SearchPageITCase extends ABCTestBase {
public SearchPageITCase(final TestConfig config, final String browser, final ApplicationType appType, final Platform platform) {
super(config, browser, appType, platform);
}
private SearchPage searchPage;
private TopNavBar topNavBar;
private CreateNewPromotionsPage createPromotionsPage;
private PromotionsPage promotionsPage;
DatePicker datePicker;
String havenErrorMessage = "Haven OnDemand returned an error while executing the search action";
@Before
public void setUp() throws MalformedURLException {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Initial thread.sleep failed");
}
topNavBar = body.getTopNavBar();
topNavBar.search("example");
searchPage = getElementFactory().getSearchPage();
searchPage.waitForSearchLoadIndicatorToDisappear();
if(getConfig().getType().equals(ApplicationType.HOSTED)) {
//Select news_ing index because I'm tired of adding lots of files to indexes
searchPage.findElement(By.xpath("//label[text()[contains(.,'Public')]]/../i")).click();
selectNewsEngIndex();
searchPage.waitForSearchLoadIndicatorToDisappear();
}
}
//TODO move this to SearchBase (and refactor code)
private void selectNewsEngIndex() {
if(getConfig().getType().equals(ApplicationType.HOSTED)) {
new WebDriverWait(getDriver(), 4).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()[contains(.,'news_eng')]]"))).click();
}
}
private void search(String searchTerm){
logger.info("Searching for: '"+searchTerm+"'");
topNavBar.search(searchTerm);
searchPage.waitForSearchLoadIndicatorToDisappear();
assertNotEquals(searchPage.getText(), contains(havenErrorMessage));
}
@Test
public void testUnmodifiedResultsToggleButton(){
new WebDriverWait(getDriver(),30).until(ExpectedConditions.visibilityOf(getElementFactory().getSearchPage()));
assertTrue("Page should be showing modified results", searchPage.modifiedResultsShown());
assertThat("Url incorrect", getDriver().getCurrentUrl(), containsString("/modified"));
searchPage.modifiedResultsCheckBox().click();
assertTrue("Page should not be showing modified results", !searchPage.modifiedResultsShown());
assertThat("Url incorrect", getDriver().getCurrentUrl(), containsString("/unmodified"));
searchPage.modifiedResultsCheckBox().click();
assertTrue("Page should be showing modified results", searchPage.modifiedResultsShown());
assertThat("Url incorrect", getDriver().getCurrentUrl(), containsString("/modified"));
}
@Test
public void testSearchBasic(){
search("dog");
assertThat("Search title text is wrong", searchPage.searchTitle().getText(), is("dog"));
search("cat");
assertThat("Search title text is wrong", searchPage.searchTitle().getText(), is("cat"));
search("ElEPhanT");
assertThat("Search title text is wrong", searchPage.searchTitle().getText(),is("ElEPhanT"));
}
@Test
public void testPromoteButton(){
searchPage.promoteTheseDocumentsButton().click();
searchPage.loadOrFadeWait();
assertThat("Promoted items bucket has not appeared", searchPage.promotionsBucket().isDisplayed());
assertThat("Promote these items button should not be enabled", searchPage.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled"));
assertThat("Promoted items count should equal 0", searchPage.promotedItemsCount(), is(0));
searchPage.searchResultCheckbox(1).click();
assertThat("Promote these items button should be enabled", !searchPage.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled"));
assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(1));
searchPage.promotionsBucketClose();
assertThat("Promoted items bucket has not appeared", searchPage.getText(), not(containsString("Select Items to Promote")));
searchPage.promoteTheseDocumentsButton().click();
searchPage.loadOrFadeWait();
assertThat("Promoted items bucket has not appeared", searchPage.promotionsBucket().isDisplayed());
assertThat("Promote these items button should not be enabled", searchPage.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled"));
assertThat("Promoted items count should equal 0", searchPage.promotedItemsCount(),is(0));
}
@Test
public void testAddFilesToPromoteBucket() {
searchPage.promoteTheseDocumentsButton().click();
searchPage.loadOrFadeWait();
for (int i = 1; i < 7; i++) {
AppElement.scrollIntoView(searchPage.searchResultCheckbox(i), getDriver());
searchPage.searchResultCheckbox(i).click();
assertThat("Promoted items count not correct", searchPage.promotedItemsCount(),is(i));
}
for (int j = 6; j > 0; j--) {
AppElement.scrollIntoView(searchPage.searchResultCheckbox(j), getDriver());
searchPage.searchResultCheckbox(j).click();
assertThat("Promoted items count not correct", searchPage.promotedItemsCount(), is(j - 1));
}
searchPage.promotionsBucketClose();
}
//TODO fix this test so it's not being run on something with an obscene amount of pages
@Ignore
@Test
public void testSearchResultsPagination() {
search("dog");
searchPage.loadOrFadeWait();
assertThat("Back to first page button is not disabled", searchPage.isBackToFirstPageButtonDisabled());
assertThat("Back a page button is not disabled", AppElement.getParent(searchPage.backPageButton()).getAttribute("class"),containsString("disabled"));
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.paginateWait();
assertThat("Back to first page button is not enabled", AppElement.getParent(searchPage.backToFirstPageButton()).getAttribute("class"),not(containsString("disabled")));
assertThat("Back a page button is not enabled", AppElement.getParent(searchPage.backPageButton()).getAttribute("class"),not(containsString("disabled")));
assertThat("Page 2 is not active", searchPage.isPageActive(2));
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.paginateWait();
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.paginateWait();
searchPage.javascriptClick(searchPage.backPageButton());
searchPage.paginateWait();
assertThat("Page 3 is not active", searchPage.isPageActive(3));
searchPage.javascriptClick(searchPage.backToFirstPageButton());
searchPage.paginateWait();
assertThat("Page 1 is not active", searchPage.isPageActive(1));
searchPage.javascriptClick(searchPage.forwardToLastPageButton());
searchPage.paginateWait();
assertThat("Forward to last page button is not disabled", AppElement.getParent(searchPage.forwardToLastPageButton()).getAttribute("class"),containsString("disabled"));
assertThat("Forward a page button is not disabled", AppElement.getParent(searchPage.forwardPageButton()).getAttribute("class"),containsString("disabled"));
final int numberOfPages = searchPage.getCurrentPageNumber();
for (int i = numberOfPages - 1; i > 0; i--) {
searchPage.javascriptClick(searchPage.backPageButton());
searchPage.paginateWait();
assertThat("Page " + String.valueOf(i) + " is not active", searchPage.isPageActive(i));
assertThat("Url incorrect", getDriver().getCurrentUrl(),endsWith(String.valueOf(i)));
}
for (int j = 2; j < numberOfPages + 1; j++) {
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.paginateWait();
assertThat("Page " + String.valueOf(j) + " is not active", searchPage.isPageActive(j));
assertThat("Url incorrect", getDriver().getCurrentUrl(),endsWith(String.valueOf(j)));
}
}
// This used to fail because the predict=false parameter was not added to our query actions
@Test
public void testPaginationAndBackButton() {
search("safe");
searchPage.forwardToLastPageButton().click();
searchPage.loadOrFadeWait();
assertThat("Forward to last page button is not disabled", searchPage.forwardToLastPageButton().getAttribute("class"),containsString("disabled"));
assertThat("Forward a page button is not disabled", searchPage.forwardPageButton().getAttribute("class"),containsString("disabled"));
final int lastPage = searchPage.getCurrentPageNumber();
getDriver().navigate().back();
assertThat("Back button has not brought the user back to the first page", searchPage.getCurrentPageNumber(),is(1));
getDriver().navigate().forward();
assertThat("Forward button has not brought the user back to the last page", searchPage.getCurrentPageNumber(), is(lastPage));
}
@Test
public void testAddDocumentToPromotionsBucket() {
search("horse");
searchPage.promoteTheseDocumentsButton().click();
searchPage.searchResultCheckbox(1).click();
assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(1));
assertThat("File in bucket description does not match file added", searchPage.getSearchResultTitle(1), equalToIgnoringCase(searchPage.bucketDocumentTitle(1)));
}
@Test
public void testPromoteTheseItemsButtonLink() {
search("fox");
searchPage.promoteTheseDocumentsButton().click();
searchPage.searchResultCheckbox(1).click();
searchPage.promoteTheseItemsButton().click();
assertThat("Create new promotions page not open", getDriver().getCurrentUrl(), endsWith("promotions/create"));
}
@Test
public void testMultiDocPromotionDrawerExpandAndPagination() {
search("freeze");
searchPage.waitForSearchLoadIndicatorToDisappear();
searchPage.createAMultiDocumentPromotion(18);
createPromotionsPage = getElementFactory().getCreateNewPromotionsPage();
createPromotionsPage.addSpotlightPromotion("Sponsored", "boat");
new WebDriverWait(getDriver(),10).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton()));
body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS);
promotionsPage = getElementFactory().getPromotionsPage();
promotionsPage.getPromotionLinkWithTitleContaining("boat").click();
PromotionsDetailPage promotionsDetailPage = getElementFactory().getPromotionsDetailPage();
assertThat(promotionsDetailPage.getText(), containsString("Trigger terms"));
new WebDriverWait(getDriver(),10).until(ExpectedConditions.visibilityOf(promotionsDetailPage.triggerAddButton()));
promotionsDetailPage.trigger("boat").click();
promotionsDetailPage.loadOrFadeWait();
new WebDriverWait(getDriver(),10).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton()));
searchPage.waitForPromotionsLoadIndicatorToDisappear();
searchPage.loadOrFadeWait();
assertThat("Summary size should equal 2", searchPage.getPromotionSummarySize(), is(2));
assertTrue("The show more promotions button is not visible", searchPage.showMorePromotionsButton().isDisplayed());
searchPage.showMorePromotions();
assertThat("Summary size should equal 5", searchPage.getPromotionSummarySize(), is(5));
searchPage.showLessPromotions();
assertThat("Summary size should equal 5", searchPage.getPromotionSummarySize(), is(2));
searchPage.showMorePromotions();
assertThat("Summary size should equal 5", searchPage.getPromotionSummarySize(), is(5));
assertThat("Back to start button should be disabled", searchPage.promotionSummaryBackToStartButton().getAttribute("class"),containsString("disabled"));
assertThat("Back button should be disabled", searchPage.promotionSummaryBackButton().getAttribute("class"),containsString("disabled"));
assertThat("Forward button should be enabled", searchPage.promotionSummaryForwardButton().getAttribute("class"), not(containsString("disabled")));
assertThat("Forward to end button should be enabled", searchPage.promotionSummaryForwardToEndButton().getAttribute("class"), not(containsString("disabled")));
searchPage.promotionSummaryForwardButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
assertThat("Back to start button should be enabled", searchPage.promotionSummaryBackToStartButton().getAttribute("class"), not(containsString("disabled")));
assertThat("Back button should be enabled", searchPage.promotionSummaryBackButton().getAttribute("class"),not(containsString("disabled")));
assertThat("Forward button should be enabled", searchPage.promotionSummaryForwardButton().getAttribute("class"), not(containsString("disabled")));
assertThat("Forward to end button should be enabled", searchPage.promotionSummaryForwardToEndButton().getAttribute("class"), not(containsString("disabled")));
searchPage.promotionSummaryForwardButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
searchPage.promotionSummaryForwardButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
assertThat("Back to start button should be enabled", searchPage.promotionSummaryBackToStartButton().getAttribute("class"),not(containsString("disabled")));
assertThat("Back button should be enabled", searchPage.promotionSummaryBackButton().getAttribute("class"), not(containsString("disabled")));
assertThat("Forward button should be disabled", searchPage.promotionSummaryForwardButton().getAttribute("class"), containsString("disabled"));
assertThat("Forward to end button should be disabled", searchPage.promotionSummaryForwardToEndButton().getAttribute("class"), containsString("disabled"));
searchPage.promotionSummaryBackButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
searchPage.promotionSummaryBackButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
searchPage.promotionSummaryBackButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
assertThat("Back to start button should be disabled", searchPage.promotionSummaryBackToStartButton().getAttribute("class"), containsString("disabled"));
searchPage.promotionSummaryForwardToEndButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
assertThat("Forward to end button should be disabled", searchPage.promotionSummaryForwardToEndButton().getAttribute("class"), containsString("disabled"));
searchPage.promotionSummaryBackToStartButton().click();
searchPage.waitForPromotionsLoadIndicatorToDisappear();
assertThat("Back button should be disabled", searchPage.promotionSummaryBackButton().getAttribute("class"),containsString("disabled"));
body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS);
promotionsPage.deleteAllPromotions();
}
@Test
public void testDocumentsRemainInBucket() {
search("cow");
searchPage.promoteTheseDocumentsButton().click();
searchPage.searchResultCheckbox(1).click();
searchPage.searchResultCheckbox(2).click();
assertThat("Promoted items count should equal 2", searchPage.promotedItemsCount(), is(2));
search("bull");
assertThat("Promoted items count should equal 2", searchPage.promotedItemsCount(), is(2));
searchPage.searchResultCheckbox(1).click();
assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(3));
search("cow");
assertThat("Promoted items count should equal 2", searchPage.promotedItemsCount(), is(3));
search("bull");
assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(3));
searchPage.searchResultCheckbox(1).click();
assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(2));
search("cow");
assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(2));
}
@Test
public void testWhitespaceSearch() {
search(" ");
assertThat("Whitespace search should not return a message as if it is a blacklisted term",
searchPage.getText(),not(containsString("All search terms are blacklisted")));
}
String searchErrorMessage = "An error occurred executing the search action";
String correctErrorMessageNotShown = "Correct error message not shown";
@Test
public void testSearchParentheses() {
List<String> testSearchTerms = Arrays.asList("(",")","()",") (",")war");
if(getConfig().getType().equals(ApplicationType.HOSTED)){
for(String searchTerm : testSearchTerms){
search(searchTerm);
assertThat(searchPage.getText(),containsString(havenErrorMessage));
}
} else if (getConfig().getType().equals(ApplicationType.ON_PREM)) {
int searchTerm = 0;
String bracketMismatch = "Bracket Mismatch in the query";
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(bracketMismatch));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(bracketMismatch));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("No valid query text supplied"));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("Terminating boolean operator"));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(bracketMismatch));
} else {
fail("Config type not recognised");
}
}
//TODO there are some which contain helpful error messages?
@Test
public void testSearchQuotationMarks() {
List<String> testSearchTerms = Arrays.asList("\"","\"\"","\" \"","\" \"","\"word","\" word","\" wo\"rd\"");
if(getConfig().getType().equals(ApplicationType.HOSTED)){
for (String searchTerm : testSearchTerms){
search(searchTerm);
assertThat(searchPage.getText(),containsString(havenErrorMessage));
}
} else if (getConfig().getType().equals(ApplicationType.ON_PREM)) {
String noValidQueryText = "No valid query text supplied";
String unclosedPhrase = "Unclosed phrase";
int searchTerm = 0;
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(noValidQueryText));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(noValidQueryText));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(noValidQueryText));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("An error occurred executing the search action"));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase));
search(testSearchTerms.get(searchTerm++));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("An error occurred executing the search action"));
assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase));
} else {
fail("Config type not recognised");
}
}
@Test
public void testDeleteDocsFromWithinBucket() {
search("sabre");
searchPage.promoteTheseDocumentsButton().click();
searchPage.searchResultCheckbox(1).click();
searchPage.searchResultCheckbox(2).click();
searchPage.searchResultCheckbox(3).click();
searchPage.searchResultCheckbox(4).click();
final List<String> bucketList = searchPage.promotionsBucketList();
final List<WebElement> bucketListElements = searchPage.promotionsBucketWebElements();
assertThat("There should be four documents in the bucket", bucketList.size(),is(4));
assertThat("promote button not displayed when bucket has documents", searchPage.promoteTheseDocumentsButton().isDisplayed());
// for (final String bucketDocTitle : bucketList) {
// final int docIndex = bucketList.indexOf(bucketDocTitle);
// assertFalse("The document title appears as blank within the bucket for document titled " + searchPage.getSearchResult(bucketList.indexOf(bucketDocTitle) + 1).getText(), bucketDocTitle.equals(""));
// searchPage.deleteDocFromWithinBucket(bucketDocTitle);
// assertThat("Checkbox still selected when doc deleted from bucket", !searchPage.searchResultCheckbox(docIndex + 1).isSelected());
// assertThat("Document not removed from bucket", searchPage.promotionsBucketList(),not(hasItem(bucketDocTitle)));
// assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(),is(3 - docIndex));
// }
for (final WebElement bucketDoc : bucketListElements) {
bucketDoc.findElement(By.cssSelector("i:nth-child(2)")).click();
}
assertThat("promote button should be disabled when bucket has no documents", searchPage.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled"));
search("tooth");
assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(), is(0));
searchPage.searchResultCheckbox(5).click();
final List<String> docTitles = new ArrayList<>();
docTitles.add(searchPage.getSearchResultTitle(5));
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.loadOrFadeWait();
searchPage.searchResultCheckbox(3).click();
docTitles.add(searchPage.getSearchResultTitle(3));
final List<String> bucketListNew = searchPage.promotionsBucketList();
assertThat("Wrong number of documents in the bucket", bucketListNew.size(),is(2));
// assertThat("", searchPage.promotionsBucketList().containsAll(docTitles));
assertThat(bucketListNew.size(),is(docTitles.size()));
for(String docTitle : docTitles){
assertThat(bucketListNew,hasItem(docTitle.toUpperCase()));
}
searchPage.deleteDocFromWithinBucket(docTitles.get(1));
assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(),is(1));
assertThat("Document should still be in the bucket", searchPage.promotionsBucketList(),hasItem(docTitles.get(0).toUpperCase()));
assertThat("Document should no longer be in the bucket", searchPage.promotionsBucketList(),not(hasItem(docTitles.get(1).toUpperCase())));
assertThat("Checkbox still selected when doc deleted from bucket", !searchPage.searchResultCheckbox(3).isSelected());
searchPage.javascriptClick(searchPage.backPageButton());
searchPage.deleteDocFromWithinBucket(docTitles.get(0));
assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(),is(0));
assertThat("Checkbox still selected when doc deleted from bucket", !searchPage.searchResultCheckbox(5).isSelected());
assertThat("promote button should be disabled when bucket has no documents", searchPage.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled"));
}
@Test
public void testViewFrame() throws InterruptedException {
search("army");
searchPage.waitForSearchLoadIndicatorToDisappear();
for (final boolean clickLogo : Arrays.asList(true, false)) {
for (int j = 1; j <= 2; j++) {
for (int i = 1; i <= 6; i++) {
final String handle = getDriver().getWindowHandle();
final String searchResultTitle = searchPage.getSearchResultTitle(i);
searchPage.loadOrFadeWait();
searchPage.viewFrameClick(clickLogo, i);
Thread.sleep(5000);
getDriver().switchTo().frame(getDriver().findElement(By.tagName("iframe")));
assertThat("View frame does not contain document: " + searchResultTitle, getDriver().findElement(By.xpath(".//*")).getText(),
containsString(searchResultTitle));
getDriver().switchTo().window(handle);
getDriver().findElement(By.xpath("//button[contains(@id, 'cboxClose')]")).click();
searchPage.loadOrFadeWait();
}
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.loadOrFadeWait();
}
}
}
@Test
public void testViewFromBucketLabel() throws InterruptedException {
search("جيمس");
searchPage.selectLanguage("Arabic");
logger.warn("Using Trimmed Titles");
search("Engineer");
//Testing in Arabic because in some instances not latin urls have been encoded incorrectly
searchPage.waitForSearchLoadIndicatorToDisappear();
searchPage.promoteTheseDocumentsButton().click();
for (int j = 1; j <=2; j++) {
for (int i = 1; i <= 3; i++) {
final String handle = getDriver().getWindowHandle();
searchPage.searchResultCheckbox(i).click();
final String docTitle = searchPage.getSearchResultTitle(i);
searchPage.getPromotionBucketElementByTrimmedTitle(docTitle).click();
Thread.sleep(5000);
getDriver().switchTo().frame(getDriver().findElement(By.tagName("iframe")));
//Using trimmedtitle is a really hacky way to get around the latin urls not being encoded (possibly, or another problem) correctly
assertThat("View frame does not contain document", getDriver().findElement(By.xpath(".//*")).getText(),containsString(docTitle));
getDriver().switchTo().window(handle);
getDriver().findElement(By.xpath("//button[contains(@id, 'cboxClose')]")).click();
searchPage.loadOrFadeWait();
}
searchPage.javascriptClick(searchPage.forwardPageButton());
searchPage.loadOrFadeWait();
}
}
@Test
public void testChangeLanguage() {
String docTitle = searchPage.getSearchResultTitle(1);
search("1");
for (final String language : Arrays.asList("English", "Afrikaans", "French", "Arabic", "Urdu", "Hindi", "Chinese", "Swahili")) {
searchPage.selectLanguage(language);
assertEquals(language, searchPage.getSelectedLanguage());
searchPage.waitForSearchLoadIndicatorToDisappear();
assertNotEquals(docTitle, searchPage.getSearchResultTitle(1));
docTitle = searchPage.getSearchResultTitle(1);
}
}
@Test
public void testBucketEmptiesWhenLanguageChangedInURL() {
search("arc");
searchPage.selectLanguage("French");
searchPage.waitForSearchLoadIndicatorToDisappear();
searchPage.promoteTheseDocumentsButton().click();
for (int i = 1; i <=4; i++) {
searchPage.searchResultCheckbox(i).click();
}
assertEquals(4, searchPage.promotionsBucketWebElements().size());
final String url = getDriver().getCurrentUrl().replace("french", "arabic");
getDriver().get(url);
searchPage = getElementFactory().getSearchPage();
searchPage.loadOrFadeWait();
assertThat("Have not navigated back to search page with modified url " + url, searchPage.promoteThisQueryButton().isDisplayed());
assertEquals(0, searchPage.promotionsBucketWebElements().size());
}
@Test
public void testLanguageDisabledWhenBucketOpened() {
//This test currently fails because language dropdown is not disabled when the promotions bucket is open
searchPage.selectLanguage("English");
search("al");
searchPage.loadOrFadeWait();
assertThat("Languages should be enabled", !searchPage.isAttributePresent(searchPage.languageButton(), "disabled"));
searchPage.promoteTheseDocumentsButton().click();
searchPage.searchResultCheckbox(1).click();
assertEquals("There should be one document in the bucket", 1, searchPage.promotionsBucketList().size());
searchPage.selectLanguage("French");
assertFalse("The promotions bucket should close when the language is changed", searchPage.promotionsBucket().isDisplayed());
searchPage.promoteTheseDocumentsButton().click();
assertEquals("There should be no documents in the bucket after changing language", 0, searchPage.promotionsBucketList().size());
searchPage.selectLanguage("English");
assertFalse("The promotions bucket should close when the language is changed", searchPage.promotionsBucket().isDisplayed());
}
@Test
public void testSearchAlternateScriptToSelectedLanguage() {
for (final String language : Arrays.asList("French", "English", "Arabic", "Urdu", "Hindi", "Chinese")) {
searchPage.selectLanguage(language);
for (final String script : Arrays.asList("निर्वाण", "العربية", "עברית", "сценарий", "latin", "ελληνικά", "ქართული", "བོད་ཡིག")) {
search(script);
searchPage.loadOrFadeWait();
assertThat("Undesired error message for language: " + language + " with script: " + script, searchPage.findElement(By.cssSelector(".search-results-view")).getText(),not(containsString("error")));
}
}
}
org.slf4j.Logger logger = LoggerFactory.getLogger(SearchPageITCase.class);
@Test
public void testFieldTextFilter() {
search("war");
searchPage.selectLanguage("English");
searchPage.selectAllIndexesOrDatabases(getConfig().getType().getName());
final String searchResultTitle = searchPage.getSearchResultTitle(1);
final String lastWordInTitle = searchPage.getLastWord(searchResultTitle);
int comparisonIndex = 0;
String comparisonString = null;
for (int i = 2; i <=6; i++) {
if (!searchPage.getLastWord(searchPage.getSearchResultTitle(i)).equals(lastWordInTitle)) {
comparisonIndex = i;
comparisonString = searchPage.getSearchResultTitle(i);
break;
}
}
if (comparisonIndex == 0) {
throw new IllegalStateException("This query is not suitable for this field text filter test");
}
searchPage.showFieldTextOptions();
searchPage.fieldTextAddButton().click();
searchPage.loadOrFadeWait();
assertThat("Field text input not visible", searchPage.fieldTextInput().isDisplayed());
assertThat("Field text confirm/tick not visible", searchPage.fieldTextTickConfirm().isDisplayed());
searchPage.fieldTextInput().clear();
searchPage.fieldTextInput().sendKeys("WILD{*" + lastWordInTitle + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.waitForSearchLoadIndicatorToDisappear();
assertThat("Field Text should not have caused an error", searchPage.getText(), not(containsString(havenErrorMessage)));
searchPage.waitForSearchLoadIndicatorToDisappear();
assertThat("Field text edit button not visible", searchPage.fieldTextEditButton().isDisplayed());
assertThat("Field text remove button not visible", searchPage.fieldTextRemoveButton().isDisplayed());
assertEquals(searchResultTitle, searchPage.getSearchResultTitle(1));
try {
assertNotEquals(searchPage.getSearchResultTitle(comparisonIndex), comparisonString);
} catch (final NoSuchElementException e) {
// The comparison document is not present
}
searchPage.fieldTextRemoveButton().click();
searchPage.loadOrFadeWait();
assertEquals(searchPage.getSearchResultTitle(comparisonIndex), comparisonString);
assertThat("Field text add button not visible", searchPage.fieldTextAddButton().isDisplayed());
assertEquals(searchResultTitle, searchPage.getSearchResultTitle(1));
}
@Test
public void testEditFieldText() {
search("boer");
searchPage.selectLanguage("Afrikaans");
searchPage.selectAllIndexesOrDatabases(getConfig().getType().getName());
searchPage.showFieldTextOptions();
searchPage.clearFieldText();
final String firstSearchResult = searchPage.getSearchResultTitle(1);
final String secondSearchResult = searchPage.getSearchResultTitle(2);
searchPage.fieldTextAddButton().click();
searchPage.loadOrFadeWait();
searchPage.fieldTextInput().clear();
searchPage.fieldTextInput().sendKeys("MATCH{" + firstSearchResult + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
searchPage.waitForSearchLoadIndicatorToDisappear();
assertThat("Field Text should not have caused an error", searchPage.getText(), not(containsString(havenErrorMessage)));
assertEquals(firstSearchResult, searchPage.getSearchResultTitle(1));
searchPage.fieldTextEditButton().click();
searchPage.fieldTextInput().clear();
searchPage.fieldTextInput().sendKeys("MATCH{" + secondSearchResult + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
searchPage.waitForSearchLoadIndicatorToDisappear();
assertThat("Field Text should not have caused an error", searchPage.getText(), not(containsString(havenErrorMessage)));
assertEquals(secondSearchResult, searchPage.getSearchResultTitle(1));
}
@Test
public void testFieldTextInputDisappearsOnOutsideClick() {
searchPage.showFieldTextOptions();
assertThat("Field text add button not visible", searchPage.fieldTextAddButton().isDisplayed());
searchPage.fieldTextAddButton().click();
assertThat("Field text add button visible", !searchPage.fieldTextAddButton().isDisplayed());
assertThat("Field text input not visible", searchPage.fieldTextInput().isDisplayed());
searchPage.fieldTextInput().click();
assertThat("Field text add button visible", !searchPage.fieldTextAddButton().isDisplayed());
assertThat("Field text input not visible", searchPage.fieldTextInput().isDisplayed());
searchPage.showRelatedConcepts();
assertThat("Field text add button not visible", searchPage.fieldTextAddButton().isDisplayed());
assertThat("Field text input visible", !searchPage.fieldTextInput().isDisplayed());
}
//TODO
@Test
public void testIdolSearchTypes() {
// searchPage.waitForSearchLoadIndicatorToDisappear();
// if(getConfig().getType().equals(ApplicationType.HOSTED)) {
// selectNewsEngIndex();
// }
search("leg");
searchPage.selectLanguage("English");
int initialSearchCount = searchPage.countSearchResults();
search("leg[2:2]");
searchPage.loadOrFadeWait();
assertThat("Failed with the following search term: leg[2:2] Search count should have reduced on initial search 'leg'",
initialSearchCount, greaterThan(searchPage.countSearchResults()));
search("red");
searchPage.loadOrFadeWait();
initialSearchCount = searchPage.countSearchResults();
search("red star");
searchPage.loadOrFadeWait();
final int secondSearchCount = searchPage.countSearchResults();
assertThat("Failed with the following search term: red star Search count should have increased on initial search: red",
initialSearchCount, lessThan(secondSearchCount));
search("\"red star\"");
searchPage.loadOrFadeWait();
final int thirdSearchCount = searchPage.countSearchResults();
assertThat("Failed with the following search term: '\"red star\"' Search count should have reduced on initial search: red star",
secondSearchCount, greaterThan(thirdSearchCount));
search("red NOT star");
searchPage.loadOrFadeWait();
final int redNotStar = searchPage.countSearchResults();
assertThat("Failed with the following search term: red NOT star Search count should have reduced on initial search: red",
initialSearchCount, greaterThan(redNotStar));
search("star");
searchPage.loadOrFadeWait();
final int star = searchPage.countSearchResults();
search("star NOT red");
searchPage.loadOrFadeWait();
final int starNotRed = searchPage.countSearchResults();
assertThat("Failed with the following search term: star NOT red Search count should have reduced on initial search: star",
star, greaterThan(starNotRed));
search("red OR star");
searchPage.loadOrFadeWait();
assertThat("Failed with the following search term: red OR star Search count should be the same as initial search: red star",
secondSearchCount, is(searchPage.countSearchResults()));
search("red AND star");
searchPage.loadOrFadeWait();
final int fourthSearchCount = searchPage.countSearchResults();
assertThat("Failed with the following search term: red AND star Search count should have reduced on initial search: red star",
secondSearchCount, greaterThan(fourthSearchCount));
assertThat("Failed with the following search term: red AND star Search count should have increased on initial search: \"red star\"",
thirdSearchCount, lessThan(fourthSearchCount));
assertThat("Sum of 'A NOT B', 'B NOT A' and 'A AND B' should equal 'A OR B' where A is: red and B is: star",
fourthSearchCount + redNotStar + starNotRed, is(secondSearchCount));
}
//TODO
@Test
public void testFieldTextRestrictionOnPromotions(){
body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS);
promotionsPage = getElementFactory().getPromotionsPage();
promotionsPage.deleteAllPromotions();
search("darth");
searchPage.selectLanguage("English");
searchPage.createAMultiDocumentPromotion(2);
createPromotionsPage = getElementFactory().getCreateNewPromotionsPage();
createPromotionsPage.addSpotlightPromotion("Sponsored", "boat");
// new WebDriverWait(getDriver(),10).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton()));
searchPage.getDocLogo(1,new WebDriverWait(getDriver(),10));
searchPage.loadOrFadeWait();
assertEquals(2, searchPage.getPromotionSummarySize());
assertEquals(2, searchPage.getPromotionSummaryLabels().size());
final List<String> initialPromotionsSummary = searchPage.promotionsSummaryList(false);
searchPage.showFieldTextOptions();
searchPage.fieldTextAddButton().click();
searchPage.fieldTextInput().sendKeys("MATCH{" + initialPromotionsSummary.get(0) + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
assertEquals(1, searchPage.getPromotionSummarySize());
assertEquals(1, searchPage.getPromotionSummaryLabels().size());
assertEquals(initialPromotionsSummary.get(0), searchPage.promotionsSummaryList(false).get(0));
searchPage.fieldTextEditButton().click();
searchPage.fieldTextInput().clear();
searchPage.fieldTextInput().sendKeys("MATCH{" + initialPromotionsSummary.get(1) + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
assertEquals(1, searchPage.getPromotionSummarySize());
assertEquals(1, searchPage.getPromotionSummaryLabels().size());
assertEquals(initialPromotionsSummary.get(1), searchPage.promotionsSummaryList(false).get(0));
}
@Test
public void testFieldTextRestrictionOnPinToPositionPromotions(){
body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS);
promotionsPage = getElementFactory().getPromotionsPage();
promotionsPage.deleteAllPromotions();
search("horse");
searchPage.selectLanguage("English");
final List<String> promotedDocs = searchPage.createAMultiDocumentPromotion(2);
createPromotionsPage = getElementFactory().getCreateNewPromotionsPage();
createPromotionsPage.navigateToTriggers();
createPromotionsPage.addSearchTrigger("duck");
createPromotionsPage.finishButton().click();
new WebDriverWait(getDriver(),10).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton()));
searchPage.waitForSearchLoadIndicatorToDisappear();
assertThat(promotedDocs.get(0) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(0)));
assertThat(promotedDocs.get(1) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(1)));
searchPage.showFieldTextOptions();
searchPage.fieldTextAddButton().click();
searchPage.fieldTextInput().sendKeys("WILD{*horse*}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
searchPage.waitForSearchLoadIndicatorToDisappear();
searchPage.loadOrFadeWait();
assertThat(promotedDocs.get(0) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(0)));
assertThat(promotedDocs.get(1) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(1))); //TODO Seems like this shouldn't be visible
assertEquals("Wrong number of results displayed", 2, searchPage.countSearchResults());
assertEquals("Wrong number of pin to position labels displayed", 2, searchPage.countPinToPositionLabels());
searchPage.fieldTextEditButton().click();
searchPage.fieldTextInput().clear();
searchPage.fieldTextInput().sendKeys("MATCH{" + promotedDocs.get(0) + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
assertEquals(promotedDocs.get(0), searchPage.getSearchResultTitle(1));
assertEquals(1, searchPage.countSearchResults());
assertEquals(1, searchPage.countPinToPositionLabels());
searchPage.fieldTextEditButton().click();
searchPage.fieldTextInput().clear();
searchPage.fieldTextInput().sendKeys("MATCH{" + promotedDocs.get(1) + "}:DRETITLE");
searchPage.fieldTextTickConfirm().click();
searchPage.loadOrFadeWait();
assertEquals(promotedDocs.get(1) + " not visible in the search title", promotedDocs.get(1), searchPage.getSearchResultTitle(1));
assertEquals("Wrong number of search results", 1, searchPage.countSearchResults());
assertEquals("Wrong nu,ber of pin to position labels", 1, searchPage.countPinToPositionLabels());
}
@Test
public void testSearchResultsCount() {
// if(getConfig().getType().equals(ApplicationType.HOSTED)) {
// selectNewsEngIndex();
// }
searchPage.selectLanguage("English");
for (final String query : Arrays.asList("dog", "chips", "dinosaur", "melon", "art")) {
logger.info("String = '" + query + "'");
search(query);
searchPage.loadOrFadeWait();
searchPage.forwardToLastPageButton().click();
searchPage.loadOrFadeWait();
final int numberOfPages = searchPage.getCurrentPageNumber();
final int lastPageDocumentsCount = searchPage.visibleDocumentsCount();
assertEquals((numberOfPages - 1) * 6 + lastPageDocumentsCount, searchPage.countSearchResults());
}
}
@Test
public void testInvalidQueryTextNoKeywordsLinksDisplayed() {
//TODO: map error messages to application type
List<String> boolOperators = Arrays.asList("OR", "WHEN", "SENTENCE", "DNEAR");
List<String> stopWords = Arrays.asList("a", "the", "of", "SOUNDEX"); //According to IDOL team SOUNDEX isn't considered a boolean operator without brackets
searchPage.selectLanguage("English");
if(getConfig().getType().equals(ApplicationType.HOSTED)) {
List<String> allTerms = ListUtils.union(boolOperators,stopWords);
for (final String searchTerm : allTerms) {
search(searchTerm);
assertThat("Correct error message not present for searchterm: " + searchTerm, searchPage.getText(), containsString("Haven OnDemand returned an error while executing the search action"));
}
} else if (getConfig().getType().equals(ApplicationType.ON_PREM)) {
for (final String searchTerm : boolOperators) {
search(searchTerm);
assertThat("Correct error message not present for searchterm: " + searchTerm + searchPage.getText(), searchPage.getText(), containsString("An error occurred executing the search action"));
assertThat("Correct error message not present for searchterm: " + searchTerm, searchPage.getText(), containsString("An error occurred fetching the query analysis."));
assertThat("Correct error message not present for searchterm: " + searchTerm, searchPage.getText(), containsString("Opening boolean operator"));
}
for (final String searchTerm : stopWords) {
search(searchTerm);
assertThat("Correct error message not present", searchPage.getText(), containsString("An error occurred executing the search action"));
assertThat("Correct error message not present", searchPage.getText(), containsString("An error occurred fetching the query analysis."));
assertThat("Correct error message not present", searchPage.getText(), containsString("No valid query text supplied"));
}
} else {
fail("Application Type not recognised");
}
}
@Test
public void testAllowSearchOfStringsThatContainBooleansWithinThem() {
final List<String> hiddenBooleansProximities = Arrays.asList("NOTed", "ANDREW", "ORder", "WHENCE", "SENTENCED", "PARAGRAPHING", "NEARLY", "SENTENCE1D", "PARAGRAPHING", "PARAGRAPH2inG", "SOUNDEXCLUSIVE", "XORING", "EORE", "DNEARLY", "WNEARING", "YNEARD", "AFTERWARDS", "BEFOREHAND", "NOTWHENERED");
for (final String hiddenBooleansProximity : hiddenBooleansProximities) {
search(hiddenBooleansProximity);
searchPage.loadOrFadeWait();
assertThat(searchPage.getText(), not(containsString("Terminating boolean operator")));
}
}
@Test
public void testFromDateFilter() throws ParseException {
// searchPage.selectAllIndexesOrDatabases(getConfig().getType().getName());
search("Dog");
final String firstResult = searchPage.getSearchResultTitle(1);
final Date date = searchPage.getDateFromResult(1);
searchPage.expandFilter(SearchBase.Filter.FILTER_BY);
searchPage.expandSubFilter(SearchBase.Filter.DATES);
searchPage.openFromDatePicker();
datePicker = new DatePicker(searchPage.$el(), getDriver());
datePicker.calendarDateSelect(date);
searchPage.closeFromDatePicker();
assertThat("Document should still be displayed", searchPage.getSearchResultTitle(1), is(firstResult));
searchPage.openFromDatePicker();
datePicker = new DatePicker(searchPage.$el(), getDriver());
datePicker.calendarDateSelect(DateUtils.addMinutes(date, 1));
searchPage.closeFromDatePicker();
assertThat("Document should not be visible. Date filter not working", searchPage.getSearchResultTitle(1), not(firstResult));
searchPage.openFromDatePicker();
datePicker = new DatePicker(searchPage.$el(), getDriver());
datePicker.calendarDateSelect(DateUtils.addMinutes(date, -1));
searchPage.closeFromDatePicker();
assertThat("Document should be visible. Date filter not working", searchPage.getSearchResultTitle(1), is(firstResult));
}
//TODO - doesn't seem to be functioning properly
@Test
public void testUntilDateFilter() throws ParseException {
// searchPage.selectAllIndexesOrDatabases(getConfig().getType().getName());
search("Dog");
final String firstResult = searchPage.getSearchResultTitle(1);
final Date date = searchPage.getDateFromResult(1);
logger.info("First Result: " + firstResult + " " + date);
searchPage.expandFilter(SearchBase.Filter.FILTER_BY);
searchPage.expandSubFilter(SearchBase.Filter.DATES);
searchPage.openUntilDatePicker();
datePicker = new DatePicker(searchPage.$el(), getDriver());
try {
datePicker.calendarDateSelect(date);
} catch (final ElementNotVisibleException e) {
for (final String label : searchPage.filterLabelList()) {
assertThat("A 'From' date filter has been applied while only an 'Until' filter was selected by the user", label,not(containsString("From: ")));
}
assertFalse("A 'From' date filter has been applied while only an 'Until' filter was selected by the user", searchPage.fromDateTextBox().getAttribute("value").isEmpty());
throw e;
}
searchPage.closeUntilDatePicker();
logger.info(searchPage.untilDateTextBox().getAttribute("value"));
assertEquals("Document should still be displayed", firstResult, searchPage.getSearchResultTitle(1));
searchPage.openUntilDatePicker();
datePicker = new DatePicker(searchPage.$el(), getDriver());
datePicker.calendarDateSelect(DateUtils.addMinutes(date, -1));
searchPage.closeUntilDatePicker();
logger.info(searchPage.untilDateTextBox().getAttribute("value"));
assertEquals("Document should not be visible. Date filter not working", firstResult, not(searchPage.getSearchResultTitle(1)));
searchPage.openUntilDatePicker();
datePicker = new DatePicker(searchPage.$el(), getDriver());
datePicker.calendarDateSelect(DateUtils.addMinutes(date, 1));
searchPage.closeUntilDatePicker();
assertEquals("Document should be visible. Date filter not working", firstResult, searchPage.getSearchResultTitle(1));
}
@Test
public void testFromDateAlwaysBeforeUntilDate() {
search("food");
searchPage.expandFilter(SearchBase.Filter.FILTER_BY);
searchPage.expandSubFilter(SearchBase.Filter.DATES);
searchPage.fromDateTextBox().sendKeys("04/05/2000 12:00 PM");
searchPage.untilDateTextBox().sendKeys("04/05/2000 12:00 PM");
searchPage.sortByRelevance();
assertEquals("Dates should be equal", searchPage.fromDateTextBox().getAttribute("value"), searchPage.untilDateTextBox().getAttribute("value"));
searchPage.loadOrFadeWait();
searchPage.fromDateTextBox().clear();
searchPage.fromDateTextBox().sendKeys("04/05/2000 12:01 PM");
//clicking sort by relevance because an outside click is needed for the changes to take place
searchPage.sortByRelevance();
// assertNotEquals("From date cannot be after the until date", searchPage.fromDateTextBox().getAttribute("value"), "04/05/2000 12:01 PM");
assertEquals("From date should be blank", searchPage.fromDateTextBox().getAttribute("value").toString(), "");
searchPage.fromDateTextBox().clear();
searchPage.fromDateTextBox().sendKeys("04/05/2000 12:00 PM");
searchPage.untilDateTextBox().clear();
searchPage.untilDateTextBox().sendKeys("04/05/2000 11:59 AM");
searchPage.sortByRelevance();
// assertEquals("Until date cannot be before the from date", searchPage.untilDateTextBox().getAttribute("value"),is(not("04/05/2000 11:59 AM")));
assertEquals("Until date should be blank",searchPage.untilDateTextBox().getAttribute("value").toString(),"");
}
@Test
public void testFromDateEqualsUntilDate() throws ParseException {
search("Search");
searchPage.expandFilter(SearchBase.Filter.FILTER_BY);
searchPage.expandSubFilter(SearchBase.Filter.DATES);
// searchPage.openFromDatePicker();
// searchPage.closeFromDatePicker();
// searchPage.openUntilDatePicker();
// searchPage.closeUntilDatePicker();
searchPage.fromDateTextBox().sendKeys("12/12/2012 12:12");
searchPage.untilDateTextBox().sendKeys("12/12/2012 12:12");
assertEquals("Datepicker dates are not equal", searchPage.fromDateTextBox().getAttribute("value"), searchPage.untilDateTextBox().getAttribute("value"));
final Date date = searchPage.getDateFromFilter(searchPage.untilDateTextBox());
searchPage.sendDateToFilter(DateUtils.addMinutes(date, 1), searchPage.untilDateTextBox());
searchPage.sortByRelevance();
assertThat(searchPage.untilDateTextBox().getAttribute("value"), is("12/12/2012 12:13"));
searchPage.sendDateToFilter(DateUtils.addMinutes(date, -1), searchPage.untilDateTextBox());
//clicking sort by relevance because an outside click is needed for the changes to take place
searchPage.sortByRelevance();
assertEquals("", searchPage.untilDateTextBox().getAttribute("value"));
}
@Test
public void testSortByRelevance() {
search("string");
searchPage.sortByRelevance();
List<Float> weights = searchPage.getWeightsOnPage(5);
logger.info("Weight of 0: " + weights.get(0));
for (int i = 0; i < weights.size() - 1; i++) {
logger.info("Weight of "+(i+1)+": "+weights.get(i+1));
assertThat("Weight of search result " + i + " is not greater that weight of search result " + (i + 1), weights.get(i), greaterThanOrEqualTo(weights.get(i + 1)));
}
searchPage.sortByDate();
searchPage.sortByRelevance();
weights = searchPage.getWeightsOnPage(5);
for (int i = 0; i < weights.size() - 1; i++) {
assertThat("Weight of search result " + i + " is not greater that weight of search result " + (i + 1), weights.get(i), greaterThanOrEqualTo(weights.get(i + 1)));
}
searchPage.sortByDate();
search("paper packages");
searchPage.sortByRelevance();
weights = searchPage.getWeightsOnPage(5);
for (int i = 0; i < weights.size() - 1; i++) {
assertThat("Weight of search result " + i + " is not greater that weight of search result " + (i + 1), weights.get(i), greaterThanOrEqualTo(weights.get(i + 1)));
}
}
@Test
public void testSearchBarTextPersistsOnRefresh() {
final String searchText = "Stay";
search(searchText);
// Change to promotions page since the search page will persist the query in the URL
body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS);
getDriver().navigate().refresh();
body = getBody();
final String newSearchText = body.getTopNavBar().getSearchBarText();
assertEquals("search bar should be blank on refresh of a page that isn't the search page", newSearchText, searchText);
}
@Test
public void testRelatedConceptsLinks() {
String queryText = "frog";
search(queryText);
assertEquals("The search bar has not retained the query text", topNavBar.getSearchBarText(), queryText);
assertThat("'You searched for' section does not include query text", searchPage.youSearchedFor(), hasItem(queryText));
assertThat("'Results for' heading text does not contain the query text", searchPage.getResultsForText(), containsString(queryText));
for (int i = 0; i < 5; i++) {
searchPage.expandFilter(SearchBase.Filter.RELATED_CONCEPTS);
searchPage.waitForRelatedConceptsLoadIndicatorToDisappear();
final int conceptsCount = searchPage.countRelatedConcepts();
assertThat("Number of related concepts exceeds 50", conceptsCount, lessThanOrEqualTo(50));
final int index = new Random().nextInt(conceptsCount);
queryText = searchPage.getRelatedConcepts().get(index).getText();
searchPage.relatedConcept(queryText).click();
searchPage.waitForSearchLoadIndicatorToDisappear();
assertEquals("The search bar has not retained the query text", topNavBar.getSearchBarText(), queryText);
final String[] words = queryText.split("\\s+");
for (final String word : words) {
assertThat("'You searched for' section does not include word: " + word + " for query text: " + queryText, searchPage.youSearchedFor(), hasItem(word));
}
assertThat("'Results for' heading text does not contain the query text: " + queryText, searchPage.getResultsForText(), containsString(queryText));
}
}
@Test
public void testRelatedConceptsDifferentInDifferentLanguages() {
search("France");
searchPage.expandFilter(SearchBase.Filter.RELATED_CONCEPTS);
searchPage.waitForRelatedConceptsLoadIndicatorToDisappear();
final List<String> englishConcepts = searchPage.webElementListToStringList(searchPage.getRelatedConcepts());
searchPage.selectLanguage("French");
searchPage.expandFilter(SearchBase.Filter.RELATED_CONCEPTS);
searchPage.waitForRelatedConceptsLoadIndicatorToDisappear();
final List<String> frenchConcepts = searchPage.webElementListToStringList(searchPage.getRelatedConcepts());
assertThat("Concepts should be different in different languages", englishConcepts, not(containsInAnyOrder(frenchConcepts.toArray())));
searchPage.selectLanguage("English");
searchPage.expandFilter(SearchBase.Filter.RELATED_CONCEPTS);
searchPage.waitForRelatedConceptsLoadIndicatorToDisappear();
final List<String> secondEnglishConcepts = searchPage.webElementListToStringList(searchPage.getRelatedConcepts());
assertThat("Related concepts have changed on second search of same query text", englishConcepts, contains(secondEnglishConcepts.toArray()));
}
@Test
public void testNavigateToLastPageOfSearchResultsAndEditUrlToTryAndNavigateFurther() {
search("nice");
searchPage.forwardToLastPageButton().click();
searchPage.waitForSearchLoadIndicatorToDisappear();
final int currentPage = searchPage.getCurrentPageNumber();
final String docTitle = searchPage.getSearchResultTitle(1);
final String url = getDriver().getCurrentUrl();
assertThat("Url and current page number are out of sync", url, containsString("nice/" + currentPage));
final String illegitimateUrl = url.replace("nice/" + currentPage, "nice/" + (currentPage + 5));
getDriver().navigate().to(illegitimateUrl);
searchPage = getElementFactory().getSearchPage();
searchPage.waitForSearchLoadIndicatorToDisappear();
//TODO failing here wrongly
assertThat("Page should still have results", searchPage.getText(), not(containsString("No results found...")));
assertThat("Page should not have thrown an error", searchPage.getText(), not(containsString(havenErrorMessage)));
assertThat("Page number should not have changed", currentPage, is(searchPage.getCurrentPageNumber()));
assertThat("Url should have reverted to original url", url, is(getDriver().getCurrentUrl()));
assertThat("Error message should not be showing", searchPage.isErrorMessageShowing(), is(false));
assertThat("Search results have changed on last page", docTitle, is(searchPage.getSearchResultTitle(1)));
}
@Test
public void testNoRelatedConceptsIfNoResultsFound() {
final String garbageQueryText = "garbagedjlsfjijlsf";
search(garbageQueryText);
String errorMessage = "Garbage text returned results. garbageQueryText string needs changed to be more garbage like";
assertThat(errorMessage, searchPage.getText(), containsString("No results found"));
assertEquals(errorMessage, 0, searchPage.countSearchResults());
searchPage.expandFilter(SearchBase.Filter.RELATED_CONCEPTS);
assertThat("If there are no search results there should be no related concepts", searchPage.getText(), containsString("No related concepts found"));
}
@Test
//TODO parametric values aren't working - file ticket
public void testParametricValuesLoads() throws InterruptedException {
searchPage.expandFilter(SearchBase.Filter.FILTER_BY);
searchPage.expandSubFilter(SearchBase.Filter.PARAMETRIC_VALUES);
Thread.sleep(20000);
assertThat("Load indicator still visible after 20 seconds", searchPage.parametricValueLoadIndicator().isDisplayed(), is(false));
}
@Test
public void testContentType(){
if(getConfig().getType().equals(ApplicationType.HOSTED)) {
selectNewsEngIndex();
searchPage.findElement(By.xpath("//label[text()[contains(.,'Public')]]/../i")).click();
}
search("Alexis");
searchPage.openParametricValuesList();
searchPage.loadOrFadeWait();
try {
new WebDriverWait(getDriver(), 30)
.withMessage("Waiting for parametric values list to load")
.until(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return !searchPage.parametricValueLoadIndicator().isDisplayed();
}
});
} catch (TimeoutException e) {
fail("Parametric values did not load");
}
int results = searchPage.filterByContentType("TEXT/PLAIN");
((JavascriptExecutor) getDriver()).executeScript("scroll(0,-400);");
searchPage.loadOrFadeWait();
searchPage.waitForSearchLoadIndicatorToDisappear();
searchPage.loadOrFadeWait();
assertThat(searchPage.searchTitle().findElement(By.xpath(".//..//span")).getText(), is("(" + results + ")"));
searchPage.forwardToLastPageButton().click();
int resultsTotal = (searchPage.getCurrentPageNumber() - 1) * 6;
resultsTotal += searchPage.visibleDocumentsCount();
assertThat(resultsTotal, is(results));
}
@Test
public void testSearchTermHighlightedInResults() {
String searchTerm = "Tiger";
search(searchTerm);
for(int i = 0; i < 3; i++) {
for (WebElement searchElement : getDriver().findElements(By.xpath("//div[contains(@class,'search-results-view')]//p//*[contains(text(),'" + searchTerm + "')]"))) {
if (searchElement.isDisplayed()) { //They can become hidden if they're too far in the summary
verifyThat(searchElement.getText(), CoreMatchers.containsString(searchTerm));
}
verifyThat(searchElement.getTagName(), is("a"));
verifyThat(searchElement.getAttribute("class"), is("query-text"));
WebElement parent = searchElement.findElement(By.xpath(".//.."));
verifyThat(parent.getTagName(), is("span"));
verifyThat(parent.getAttribute("class"), CoreMatchers.containsString("label"));
}
searchPage.forwardPageButton().click();
}
}
}
| test base
| integration-tests-common/src/test/java/com/autonomy/abc/search/SearchPageITCase.java | test base | <ide><path>ntegration-tests-common/src/test/java/com/autonomy/abc/search/SearchPageITCase.java
<ide> import com.autonomy.abc.selenium.page.promotions.PromotionsPage;
<ide> import com.autonomy.abc.selenium.page.search.SearchBase;
<ide> import com.autonomy.abc.selenium.page.search.SearchPage;
<add>import com.autonomy.abc.selenium.search.IndexFilter;
<add>import com.autonomy.abc.selenium.search.Search;
<ide> import com.hp.autonomy.frontend.selenium.util.AppElement;
<ide> import org.apache.commons.collections.ListUtils;
<ide> import org.apache.commons.lang.time.DateUtils;
<ide> searchPage.forwardPageButton().click();
<ide> }
<ide> }
<add>
<add> @Test
<add> //CSA1708
<add> public void testParametricLabelsNotUndefined(){
<add> new Search(getApplication(),getElementFactory(),"simpsons").applyFilter(new IndexFilter("default_index")).apply();
<add>
<add> searchPage.filterByContentType("TEXT/HTML");
<add>
<add> for(WebElement filter : searchPage.findElements(By.cssSelector(".filter-display-view span"))){
<add> assertThat(filter.getText().toLowerCase(),not(containsString("undefined")));
<add> }
<add> }
<ide> } |
|
JavaScript | mit | fb21d32c44465b92c35a7ed32353ecc18991ff4c | 0 | mschinis/ember-cli,akatov/ember-cli,EricSchank/ember-cli,johnotander/ember-cli,kriswill/ember-cli,cibernox/ember-cli,gfvcastro/ember-cli,selvagsz/ember-cli,samselikoff/ember-cli,princeofdarkness76/ember-cli,slindberg/ember-cli,alefteris/ember-cli,supabok/ember-cli,mattmarcum/ember-cli,mohlek/ember-cli,taras/ember-cli,eoinkelly/ember-cli,asakusuma/ember-cli,quaertym/ember-cli,joliss/ember-cli,josemarluedke/ember-cli,josemarluedke/ember-cli,scalus/ember-cli,xcambar/ember-cli,supabok/ember-cli,pzuraq/ember-cli,akatov/ember-cli,dosco/ember-cli,typeoneerror/ember-cli,michael-k/ember-cli,calderas/ember-cli,twokul/ember-cli,eoinkelly/ember-cli,kategengler/ember-cli,dschmidt/ember-cli,ballPointPenguin/ember-cli,mike-north/ember-cli,Restuta/ember-cli,seawatts/ember-cli,raytiley/ember-cli,pzuraq/ember-cli,kriswill/ember-cli,beatle/ember-cli,ember-cli/ember-cli,pixelhandler/ember-cli,dosco/ember-cli,jrjohnson/ember-cli,pzuraq/ember-cli,sivakumar-kailasam/ember-cli,searls/ember-cli,gmurphey/ember-cli,ef4/ember-cli,yaymukund/ember-cli,yaymukund/ember-cli,samselikoff/ember-cli,ServiceTo/ember-cli,trabus/ember-cli,twokul/ember-cli,marcioj/ember-cli,rtablada/ember-cli,jrjohnson/ember-cli,kanongil/ember-cli,kamalaknn/ember-cli,Restuta/ember-cli,josemarluedke/ember-cli,tsing80/ember-cli,ServiceTo/ember-cli,dukex/ember-cli,johnotander/ember-cli,comlaterra/ember-cli,akatov/ember-cli,seanpdoyle/ember-cli,lazybensch/ember-cli,aceofspades/ember-cli,EricSchank/ember-cli,airportyh/ember-cli,pangratz/ember-cli,joostdevries/ember-cli,acorncom/ember-cli,olegdovger/ember-cli,oss-practice/ember-cli,ro0gr/ember-cli,EricSchank/ember-cli,jonathanKingston/ember-cli,jayphelps/ember-cli,zanemayo/ember-cli,nruth/ember-cli,gfvcastro/ember-cli,ember-cli/ember-cli,princeofdarkness76/ember-cli,csantero/ember-cli,calderas/ember-cli,martypenner/ember-cli,jgwhite/ember-cli,tobymarsden/ember-cli,trentmwillis/ember-cli,BrianSipple/ember-cli,trentmwillis/ember-cli,williamsbdev/ember-cli,lancedikson/ember-cli,alefteris/ember-cli,dschmidt/ember-cli,rodyhaddad/ember-cli,jgwhite/ember-cli,johnotander/ember-cli,eliotsykes/ember-cli,alefteris/ember-cli,joostdevries/ember-cli,igorT/ember-cli,lazybensch/ember-cli,oss-practice/ember-cli,kanongil/ember-cli,princeofdarkness76/ember-cli,johanneswuerbach/ember-cli,pixelhandler/ember-cli,bevacqua/ember-cli,seawatts/ember-cli,martypenner/ember-cli,lazybensch/ember-cli,mixonic/ember-cli,seanpdoyle/ember-cli,pangratz/ember-cli,martndemus/ember-cli,mike-north/ember-cli,sivakumar-kailasam/ember-cli,raytiley/ember-cli,ro0gr/ember-cli,marcioj/ember-cli,ballPointPenguin/ember-cli,patocallaghan/ember-cli,abuiles/ember-cli,noslouch/ember-cli,comlaterra/ember-cli,chadhietala/ember-cli,nathanhammond/ember-cli,beatle/ember-cli,givanse/ember-cli,DanielOchoa/ember-cli,noslouch/ember-cli,fpauser/ember-cli,gfvcastro/ember-cli,nruth/ember-cli,szines/ember-cli,ro0gr/ember-cli,dukex/ember-cli,xtian/ember-cli,ianstarz/ember-cli,jayphelps/ember-cli,cibernox/ember-cli,kriswill/ember-cli,felixrieseberg/ember-cli,acorncom/ember-cli,felixrieseberg/ember-cli,rtablada/ember-cli,rtablada/ember-cli,chadhietala/ember-cli,yaymukund/ember-cli,jayphelps/ember-cli,lazybensch/ember-cli,jcope2013/ember-cli,pixelhandler/ember-cli,xtian/ember-cli,airportyh/ember-cli,givanse/ember-cli,nathanhammond/ember-cli,comlaterra/ember-cli,zanemayo/ember-cli,romulomachado/ember-cli,rot26/ember-cli,xcambar/ember-cli,rodyhaddad/ember-cli,HeroicEric/ember-cli,xiujunma/ember-cli,martndemus/ember-cli,szines/ember-cli,kellyselden/ember-cli,searls/ember-cli,taras/ember-cli,eliotsykes/ember-cli,jonathanKingston/ember-cli,xcambar/ember-cli,makepanic/ember-cli,calderas/ember-cli,rodyhaddad/ember-cli,mattmarcum/ember-cli,Turbo87/ember-cli,eoinkelly/ember-cli,yapplabs/ember-cli,jcope2013/ember-cli,joliss/ember-cli,fpauser/ember-cli,nathanhammond/ember-cli,raytiley/ember-cli,selvagsz/ember-cli,dukex/ember-cli,joaohornburg/ember-cli,rondale-sc/ember-cli,mschinis/ember-cli,bmac/ember-cli,joaohornburg/ember-cli,sivakumar-kailasam/ember-cli,eoinkelly/ember-cli,bmac/ember-cli,martndemus/ember-cli,martypenner/ember-cli,zanemayo/ember-cli,aceofspades/ember-cli,kamalaknn/ember-cli,HeroicEric/ember-cli,comlaterra/ember-cli,mohlek/ember-cli,calderas/ember-cli,tsing80/ember-cli,alexdiliberto/ember-cli,raytiley/ember-cli,code0100fun/ember-cli,scalus/ember-cli,noslouch/ember-cli,ember-cli/ember-cli,mike-north/ember-cli,makepanic/ember-cli,jasonmit/ember-cli,olegdovger/ember-cli,jcope2013/ember-cli,tobymarsden/ember-cli,airportyh/ember-cli,olegdovger/ember-cli,mohlek/ember-cli,romulomachado/ember-cli,dukex/ember-cli,cibernox/ember-cli,elwayman02/ember-cli,mschinis/ember-cli,seanpdoyle/ember-cli,ballPointPenguin/ember-cli,Restuta/ember-cli,eliotsykes/ember-cli,typeoneerror/ember-cli,romulomachado/ember-cli,greyhwndz/ember-cli,BrianSipple/ember-cli,rot26/ember-cli,ianstarz/ember-cli,blimmer/ember-cli,blimmer/ember-cli,mixonic/ember-cli,olegdovger/ember-cli,eccegordo/ember-cli,lancedikson/ember-cli,mohlek/ember-cli,ballPointPenguin/ember-cli,mixonic/ember-cli,typeoneerror/ember-cli,felixrieseberg/ember-cli,ef4/ember-cli,kellyselden/ember-cli,Turbo87/ember-cli,code0100fun/ember-cli,igorT/ember-cli,rickharrison/ember-cli,mixonic/ember-cli,taras/ember-cli,xiujunma/ember-cli,ServiceTo/ember-cli,twokul/ember-cli,ro0gr/ember-cli,greyhwndz/ember-cli,Turbo87/ember-cli,gmurphey/ember-cli,bevacqua/ember-cli,ef4/ember-cli,jcope2013/ember-cli,givanse/ember-cli,dosco/ember-cli,beatle/ember-cli,nathanhammond/ember-cli,buschtoens/ember-cli,martndemus/ember-cli,seawatts/ember-cli,thoov/ember-cli,alexdiliberto/ember-cli,kellyselden/ember-cli,noslouch/ember-cli,michael-k/ember-cli,acorncom/ember-cli,romulomachado/ember-cli,trentmwillis/ember-cli,raycohen/ember-cli,maxcal/ember-cli,quaertym/ember-cli,kanongil/ember-cli,abuiles/ember-cli,michael-k/ember-cli,bevacqua/ember-cli,quaertym/ember-cli,runspired/ember-cli,Turbo87/ember-cli,tobymarsden/ember-cli,greyhwndz/ember-cli,DanielOchoa/ember-cli,johanneswuerbach/ember-cli,trabus/ember-cli,gmurphey/ember-cli,szines/ember-cli,mschinis/ember-cli,balinterdi/ember-cli,kriswill/ember-cli,pixelhandler/ember-cli,DanielOchoa/ember-cli,samselikoff/ember-cli,ianstarz/ember-cli,code0100fun/ember-cli,patocallaghan/ember-cli,balinterdi/ember-cli,mike-north/ember-cli,trabus/ember-cli,akatov/ember-cli,searls/ember-cli,rot26/ember-cli,BrianSipple/ember-cli,xiujunma/ember-cli,johanneswuerbach/ember-cli,joaohornburg/ember-cli,makepanic/ember-cli,xcambar/ember-cli,selvagsz/ember-cli,blimmer/ember-cli,coderly/ember-cli,airportyh/ember-cli,trentmwillis/ember-cli,acorncom/ember-cli,josemarluedke/ember-cli,eccegordo/ember-cli,xtian/ember-cli,taras/ember-cli,jasonmit/ember-cli,xiujunma/ember-cli,marcioj/ember-cli,slindberg/ember-cli,csantero/ember-cli,patocallaghan/ember-cli,rtablada/ember-cli,kamalaknn/ember-cli,code0100fun/ember-cli,yapplabs/ember-cli,HeroicEric/ember-cli,patocallaghan/ember-cli,samselikoff/ember-cli,jasonmit/ember-cli,nruth/ember-cli,thoov/ember-cli,joaohornburg/ember-cli,yaymukund/ember-cli,elwayman02/ember-cli,raycohen/ember-cli,buschtoens/ember-cli,blimmer/ember-cli,thoov/ember-cli,johnotander/ember-cli,twokul/ember-cli,pangratz/ember-cli,coderly/ember-cli,abuiles/ember-cli,ef4/ember-cli,typeoneerror/ember-cli,lancedikson/ember-cli,michael-k/ember-cli,gfvcastro/ember-cli,BrianSipple/ember-cli,sivakumar-kailasam/ember-cli,jonathanKingston/ember-cli,trabus/ember-cli,rondale-sc/ember-cli,kellyselden/ember-cli,eccegordo/ember-cli,williamsbdev/ember-cli,ServiceTo/ember-cli,bevacqua/ember-cli,lancedikson/ember-cli,scalus/ember-cli,marcioj/ember-cli,williamsbdev/ember-cli,selvagsz/ember-cli,rickharrison/ember-cli,eliotsykes/ember-cli,abuiles/ember-cli,runspired/ember-cli,EricSchank/ember-cli,tsing80/ember-cli,cibernox/ember-cli,kategengler/ember-cli,jgwhite/ember-cli,williamsbdev/ember-cli,ianstarz/ember-cli,quaertym/ember-cli,alefteris/ember-cli,csantero/ember-cli,zanemayo/ember-cli,asakusuma/ember-cli,jgwhite/ember-cli,eccegordo/ember-cli,rot26/ember-cli,pzuraq/ember-cli,scalus/ember-cli,pangratz/ember-cli,joliss/ember-cli,greyhwndz/ember-cli,jasonmit/ember-cli,princeofdarkness76/ember-cli,HeroicEric/ember-cli,dosco/ember-cli,coderly/ember-cli,Restuta/ember-cli,runspired/ember-cli,martypenner/ember-cli,runspired/ember-cli,seanpdoyle/ember-cli,joostdevries/ember-cli,tsing80/ember-cli,coderly/ember-cli,kamalaknn/ember-cli,fpauser/ember-cli,joliss/ember-cli,szines/ember-cli,kanongil/ember-cli,thoov/ember-cli,johanneswuerbach/ember-cli,givanse/ember-cli,DanielOchoa/ember-cli,gmurphey/ember-cli,maxcal/ember-cli,maxcal/ember-cli,beatle/ember-cli,maxcal/ember-cli,tobymarsden/ember-cli,rodyhaddad/ember-cli,alexdiliberto/ember-cli,seawatts/ember-cli,joostdevries/ember-cli,nruth/ember-cli,searls/ember-cli,jayphelps/ember-cli,csantero/ember-cli,rwjblue/ember-cli,alexdiliberto/ember-cli,xtian/ember-cli,fpauser/ember-cli,jonathanKingston/ember-cli,makepanic/ember-cli | 'use strict';
var assert = require('../helpers/assert');
var Command = require('../../lib/command');
var command;
var called = false;
var ui = {};
beforeEach(function() {
command = new Command({
name: 'fake-command',
run: function() {}
});
command.leek = {
track: function() {
called = true;
}
};
});
afterEach(function() {
command = null;
});
describe('Leek', function() {
it('track gets invoked on command.run()', function() {
command.run(ui, {
cliArgs: []
}, {});
assert.ok(called);
});
});
| tests/unit/leek-test.js | 'use strict';
var assert = require('../helpers/assert');
var Command = require('../../lib/command');
var command;
var called = false;
var ui = {};
beforeEach(function() {
command = new Command({
name: 'fake-command',
run: function() {}
});
command.leek = {
track: function() {
called = true;
}
};
});
afterEach(function() {
command = null;
});
describe('Leek', function() {
it('track gets invoked on command.run()', function() {
command.run(ui, {
cliArgs: []
}, {});
assert.ok(called);
});
});
| fixed per stefanpenner feedback
| tests/unit/leek-test.js | fixed per stefanpenner feedback | <ide><path>ests/unit/leek-test.js
<ide> var assert = require('../helpers/assert');
<ide> var Command = require('../../lib/command');
<ide> var command;
<del>var called = false;
<add>var called = false;
<ide> var ui = {};
<ide>
<ide> beforeEach(function() { |
|
Java | mit | bb675f46fa9a294270215bc28f782ad219237a47 | 0 | cBioPortal/genome-nexus,genome-nexus/genome-nexus,cBioPortal/genome-nexus,genome-nexus/genome-nexus,cBioPortal/genome-nexus | package org.cbioportal.genome_nexus.service.internal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cbioportal.genome_nexus.model.my_variant_info_model.MyVariantInfo;
import org.cbioportal.genome_nexus.model.VariantAnnotation;
import org.cbioportal.genome_nexus.service.MyVariantInfoService;
import org.cbioportal.genome_nexus.service.cached.CachedMyVariantInfoFetcher;
import org.cbioportal.genome_nexus.service.exception.MyVariantInfoNotFoundException;
import org.cbioportal.genome_nexus.service.exception.MyVariantInfoWebServiceException;
import org.cbioportal.genome_nexus.service.exception.ResourceMappingException;
import org.cbioportal.genome_nexus.service.exception.VariantAnnotationNotFoundException;
import org.cbioportal.genome_nexus.service.exception.VariantAnnotationWebServiceException;
import org.cbioportal.genome_nexus.util.Hgvs;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
@Service
public class MyVariantInfoServiceImpl implements MyVariantInfoService
{
private static final Log LOG = LogFactory.getLog(MyVariantInfoServiceImpl.class);
private final CachedMyVariantInfoFetcher cachedExternalResourceFetcher;
@Autowired
public MyVariantInfoServiceImpl(CachedMyVariantInfoFetcher cachedExternalResourceFetcher)
{
this.cachedExternalResourceFetcher = cachedExternalResourceFetcher;
}
/**
* @param variant hgvs variant (ex: 7:g.140453136A>T)
*/
public MyVariantInfo getMyVariantInfoByHgvsVariant(String variant)
throws VariantAnnotationNotFoundException, VariantAnnotationWebServiceException,
MyVariantInfoWebServiceException, MyVariantInfoNotFoundException
{
return this.getMyVariantInfoByMyVariantInfoVariant(buildRequest(variant));
}
/**
* @param variants hgvs variants (ex: 7:g.140453136A>T)
*/
public List<MyVariantInfo> getMyVariantInfoByHgvsVariant(List<String> variants)
{
List<MyVariantInfo> myVariantInfos = Collections.emptyList();
Map<String, String> queryToVariant = this.queryToVariant(variants);
List<String> queryVariants = new ArrayList<>(queryToVariant.keySet());
try {
myVariantInfos = this.getMyVariantInfoByMyVariantInfoVariant(queryVariants);
// manually set the original hgvs variant field
for (MyVariantInfo myVariantInfo: myVariantInfos) {
// myVariantInfo.getVariant() will return my_variant_info query id (e.g. chr7:g.140453136A>T)
// queryToVariant.get() will return genome nexus query id (e.g. 7:g.140453136A>T)
myVariantInfo.setHgvs(queryToVariant.get(myVariantInfo.getVariant()));
}
} catch (MyVariantInfoWebServiceException e) {
LOG.warn(e.getResponseBody());
}
return myVariantInfos;
}
public MyVariantInfo getMyVariantInfoByAnnotation(VariantAnnotation annotation)
throws MyVariantInfoNotFoundException, MyVariantInfoWebServiceException
{
// get hgvsg from VEP (annotation.getId() might not be in hgvsg format)
String hgvsg = annotation.getHgvsg();
if (hgvsg != null) {
return this.getMyVariantInfoByMyVariantInfoVariant(buildRequest(hgvsg));
}
else {
return null;
}
}
@Override
public List<MyVariantInfo> getMyVariantInfoByAnnotation(List<VariantAnnotation> annotations)
throws MyVariantInfoWebServiceException
{
return this.getMyVariantInfoByHgvsVariant(
annotations.stream().map(VariantAnnotation::getHgvsg).collect(Collectors.toList())
);
}
/**
* @param variant my variant info variant (ex: chr1:g.35367G>A)
*/
public MyVariantInfo getMyVariantInfoByMyVariantInfoVariant(String variant)
throws MyVariantInfoNotFoundException, MyVariantInfoWebServiceException
{
Optional<MyVariantInfo> myVariantInfo = null;
try {
// get the annotation from the web service and save it to the DB
myVariantInfo = Optional.ofNullable(cachedExternalResourceFetcher.fetchAndCache(variant));
// manually set the original hgvs variant field
myVariantInfo.ifPresent(m -> m.setHgvs(variant));
} catch (ResourceMappingException e) {
throw new MyVariantInfoWebServiceException(e.getMessage());
} catch (HttpClientErrorException e) {
throw new MyVariantInfoWebServiceException(e.getResponseBodyAsString(), e.getStatusCode());
} catch (ResourceAccessException e) {
throw new MyVariantInfoWebServiceException(e.getMessage());
}
try {
return myVariantInfo.get();
} catch (NoSuchElementException e) {
throw new MyVariantInfoNotFoundException(variant);
}
}
/**
* @param variants my variant info variants (ex: [chr1:g.35367G>A, chr6:g.152708291G>A])
*/
private List<MyVariantInfo> getMyVariantInfoByMyVariantInfoVariant(List<String> variants)
throws MyVariantInfoWebServiceException
{
try {
// get the annotations from the web service and save it to the DB
return cachedExternalResourceFetcher.fetchAndCache(variants);
} catch (ResourceMappingException e) {
throw new MyVariantInfoWebServiceException(e.getMessage());
} catch (HttpClientErrorException e) {
throw new MyVariantInfoWebServiceException(e.getResponseBodyAsString(), e.getStatusCode());
} catch (ResourceAccessException e) {
throw new MyVariantInfoWebServiceException(e.getMessage());
}
}
@NotNull
private String buildRequest(String variant)
{
return Hgvs.addChrPrefix(Hgvs.removeDeletedBases(variant));
}
/**
* Creates a LinkedHashMap to make sure that we keep the original input order.
* Key is the string created by buildRequest method.
* Value is the original variant string
*
* @param variants list of original input variants
* @return LinkedHashMap
*/
private Map<String, String> queryToVariant(List<String> variants) {
return variants.stream()
.filter(Objects::nonNull)
.collect(Collectors.toMap(
this::buildRequest,
v -> v,
(u, v) -> v,
LinkedHashMap::new
)
);
}
}
| service/src/main/java/org/cbioportal/genome_nexus/service/internal/MyVariantInfoServiceImpl.java | package org.cbioportal.genome_nexus.service.internal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cbioportal.genome_nexus.model.my_variant_info_model.MyVariantInfo;
import org.cbioportal.genome_nexus.model.VariantAnnotation;
import org.cbioportal.genome_nexus.service.MyVariantInfoService;
import org.cbioportal.genome_nexus.service.cached.CachedMyVariantInfoFetcher;
import org.cbioportal.genome_nexus.service.exception.MyVariantInfoNotFoundException;
import org.cbioportal.genome_nexus.service.exception.MyVariantInfoWebServiceException;
import org.cbioportal.genome_nexus.service.exception.ResourceMappingException;
import org.cbioportal.genome_nexus.service.exception.VariantAnnotationNotFoundException;
import org.cbioportal.genome_nexus.service.exception.VariantAnnotationWebServiceException;
import org.cbioportal.genome_nexus.util.Hgvs;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
@Service
public class MyVariantInfoServiceImpl implements MyVariantInfoService
{
private static final Log LOG = LogFactory.getLog(MyVariantInfoServiceImpl.class);
private final CachedMyVariantInfoFetcher cachedExternalResourceFetcher;
@Autowired
public MyVariantInfoServiceImpl(CachedMyVariantInfoFetcher cachedExternalResourceFetcher)
{
this.cachedExternalResourceFetcher = cachedExternalResourceFetcher;
}
/**
* @param variant hgvs variant (ex: 7:g.140453136A>T)
*/
public MyVariantInfo getMyVariantInfoByHgvsVariant(String variant)
throws VariantAnnotationNotFoundException, VariantAnnotationWebServiceException,
MyVariantInfoWebServiceException, MyVariantInfoNotFoundException
{
return this.getMyVariantInfoByMyVariantInfoVariant(buildRequest(variant));
}
/**
* @param variants hgvs variants (ex: 7:g.140453136A>T)
*/
public List<MyVariantInfo> getMyVariantInfoByHgvsVariant(List<String> variants)
{
List<MyVariantInfo> myVariantInfos = Collections.emptyList();
Map<String, String> queryToVariant = this.queryToVariant(variants);
List<String> queryVariants = new ArrayList<>(queryToVariant.keySet());
try {
myVariantInfos = this.getMyVariantInfoByMyVariantInfoVariant(queryVariants);
// manually set the original hgvs variant field
for (MyVariantInfo myVariantInfo: myVariantInfos) {
myVariantInfo.setHgvs(queryToVariant.get(myVariantInfo.getQuery()));
}
} catch (MyVariantInfoWebServiceException e) {
LOG.warn(e.getResponseBody());
}
return myVariantInfos;
}
public MyVariantInfo getMyVariantInfoByAnnotation(VariantAnnotation annotation)
throws MyVariantInfoNotFoundException, MyVariantInfoWebServiceException
{
// get hgvsg from VEP (annotation.getId() might not be in hgvsg format)
String hgvsg = annotation.getHgvsg();
if (hgvsg != null) {
return this.getMyVariantInfoByMyVariantInfoVariant(buildRequest(hgvsg));
}
else {
return null;
}
}
@Override
public List<MyVariantInfo> getMyVariantInfoByAnnotation(List<VariantAnnotation> annotations)
throws MyVariantInfoWebServiceException
{
return this.getMyVariantInfoByHgvsVariant(
annotations.stream().map(VariantAnnotation::getHgvsg).collect(Collectors.toList())
);
}
/**
* @param variant my variant info variant (ex: chr1:g.35367G>A)
*/
public MyVariantInfo getMyVariantInfoByMyVariantInfoVariant(String variant)
throws MyVariantInfoNotFoundException, MyVariantInfoWebServiceException
{
Optional<MyVariantInfo> myVariantInfo = null;
try {
// get the annotation from the web service and save it to the DB
myVariantInfo = Optional.ofNullable(cachedExternalResourceFetcher.fetchAndCache(variant));
// manually set the original hgvs variant field
myVariantInfo.ifPresent(m -> m.setHgvs(variant));
} catch (ResourceMappingException e) {
throw new MyVariantInfoWebServiceException(e.getMessage());
} catch (HttpClientErrorException e) {
throw new MyVariantInfoWebServiceException(e.getResponseBodyAsString(), e.getStatusCode());
} catch (ResourceAccessException e) {
throw new MyVariantInfoWebServiceException(e.getMessage());
}
try {
return myVariantInfo.get();
} catch (NoSuchElementException e) {
throw new MyVariantInfoNotFoundException(variant);
}
}
/**
* @param variants my variant info variants (ex: [chr1:g.35367G>A, chr6:g.152708291G>A])
*/
private List<MyVariantInfo> getMyVariantInfoByMyVariantInfoVariant(List<String> variants)
throws MyVariantInfoWebServiceException
{
try {
// get the annotations from the web service and save it to the DB
return cachedExternalResourceFetcher.fetchAndCache(variants);
} catch (ResourceMappingException e) {
throw new MyVariantInfoWebServiceException(e.getMessage());
} catch (HttpClientErrorException e) {
throw new MyVariantInfoWebServiceException(e.getResponseBodyAsString(), e.getStatusCode());
} catch (ResourceAccessException e) {
throw new MyVariantInfoWebServiceException(e.getMessage());
}
}
@NotNull
private String buildRequest(String variant)
{
return Hgvs.addChrPrefix(Hgvs.removeDeletedBases(variant));
}
/**
* Creates a LinkedHashMap to make sure that we keep the original input order.
* Key is the string created by buildRequest method.
* Value is the original variant string
*
* @param variants list of original input variants
* @return LinkedHashMap
*/
private Map<String, String> queryToVariant(List<String> variants) {
return variants.stream()
.filter(Objects::nonNull)
.collect(Collectors.toMap(
this::buildRequest,
v -> v,
(u, v) -> v,
LinkedHashMap::new
)
);
}
}
| fix my variant info missing in BRCA2 mutations
| service/src/main/java/org/cbioportal/genome_nexus/service/internal/MyVariantInfoServiceImpl.java | fix my variant info missing in BRCA2 mutations | <ide><path>ervice/src/main/java/org/cbioportal/genome_nexus/service/internal/MyVariantInfoServiceImpl.java
<ide> myVariantInfos = this.getMyVariantInfoByMyVariantInfoVariant(queryVariants);
<ide> // manually set the original hgvs variant field
<ide> for (MyVariantInfo myVariantInfo: myVariantInfos) {
<del> myVariantInfo.setHgvs(queryToVariant.get(myVariantInfo.getQuery()));
<add> // myVariantInfo.getVariant() will return my_variant_info query id (e.g. chr7:g.140453136A>T)
<add> // queryToVariant.get() will return genome nexus query id (e.g. 7:g.140453136A>T)
<add> myVariantInfo.setHgvs(queryToVariant.get(myVariantInfo.getVariant()));
<ide> }
<ide> } catch (MyVariantInfoWebServiceException e) {
<ide> LOG.warn(e.getResponseBody()); |
|
Java | apache-2.0 | 76c809a78b929b7e4a7652a38da57641f0f602fb | 0 | Erudika/scoold,Erudika/scoold,Erudika/scoold,Erudika/scoold | /*
* Copyright 2013-2022 Erudika. https://erudika.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 issues and patches go to: https://github.com/erudika
*/
package com.erudika.scoold.controllers;
import com.erudika.para.client.ParaClient;
import com.erudika.para.core.App;
import com.erudika.para.core.ParaObject;
import com.erudika.para.core.Sysprop;
import com.erudika.para.core.Tag;
import com.erudika.para.core.User;
import com.erudika.para.core.Webhook;
import com.erudika.para.core.utils.Config;
import com.erudika.para.core.utils.Pager;
import com.erudika.para.core.utils.Para;
import com.erudika.para.core.utils.ParaObjectUtils;
import com.erudika.para.core.utils.Utils;
import com.erudika.scoold.ScooldConfig;
import static com.erudika.scoold.ScooldServer.ADMINLINK;
import static com.erudika.scoold.ScooldServer.HOMEPAGE;
import static com.erudika.scoold.ScooldServer.SIGNINLINK;
import com.erudika.scoold.core.Comment;
import com.erudika.scoold.core.Post;
import com.erudika.scoold.core.Profile;
import com.erudika.scoold.core.Question;
import com.erudika.scoold.core.Reply;
import com.erudika.scoold.utils.ScooldUtils;
import com.erudika.scoold.utils.Version;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.nimbusds.jwt.SignedJWT;
import com.typesafe.config.ConfigValue;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
/**
*
* @author Alex Bogdanovski [[email protected]]
*/
@Controller
@RequestMapping("/admin")
public class AdminController {
private static final Logger logger = LoggerFactory.getLogger(AdminController.class);
private static final ScooldConfig CONF = ScooldUtils.getConfig();
private static final int MAX_SPACES = 10; // Hey! It's cool to edit this, but please consider buying Scoold Pro! :)
private final String soDateFormat1 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private final String soDateFormat2 = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private final ScooldUtils utils;
private final ParaClient pc;
@Inject
public AdminController(ScooldUtils utils) {
this.utils = utils;
this.pc = utils.getParaClient();
}
@GetMapping
public String get(HttpServletRequest req, Model model) {
if (utils.isAuthenticated(req) && !utils.isAdmin(utils.getAuthUser(req))) {
return "redirect:" + HOMEPAGE;
} else if (!utils.isAuthenticated(req)) {
return "redirect:" + SIGNINLINK + "?returnto=" + ADMINLINK;
}
Map<String, Object> configMap = new LinkedHashMap<String, Object>();
for (Map.Entry<String, ConfigValue> entry : CONF.getConfig().entrySet()) {
ConfigValue value = entry.getValue();
configMap.put(entry.getKey(), value != null ? value.unwrapped() : "-");
}
Pager itemcount = utils.getPager("page", req);
Pager itemcount1 = utils.getPager("page1", req);
itemcount.setLimit(40);
model.addAttribute("path", "admin.vm");
model.addAttribute("title", utils.getLang(req).get("administration.title"));
model.addAttribute("configMap", configMap);
model.addAttribute("version", pc.getServerVersion());
model.addAttribute("endpoint", CONF.redirectUri());
model.addAttribute("paraapp", CONF.paraAccessKey());
model.addAttribute("spaces", pc.findQuery("scooldspace", "*", itemcount));
model.addAttribute("webhooks", pc.findQuery(Utils.type(Webhook.class), "*", itemcount1));
model.addAttribute("scooldimports", pc.findQuery("scooldimport", "*", new Pager(7)));
model.addAttribute("coreScooldTypes", utils.getCoreScooldTypes());
model.addAttribute("customHookEvents", utils.getCustomHookEvents());
model.addAttribute("apiKeys", utils.getApiKeys());
model.addAttribute("apiKeysExpirations", utils.getApiKeysExpirations());
model.addAttribute("itemcount", itemcount);
model.addAttribute("itemcount1", itemcount1);
model.addAttribute("isDefaultSpacePublic", utils.isDefaultSpacePublic());
model.addAttribute("scooldVersion", Version.getVersion());
model.addAttribute("scooldRevision", Version.getRevision());
String importedCount = req.getParameter("imported");
if (importedCount != null) {
if (req.getParameter("success") != null) {
model.addAttribute("infoStripMsg", "Started a new data import task. ");
} else {
model.addAttribute("infoStripMsg", "Data import task failed! The archive was partially imported.");
}
}
Sysprop theme = utils.getCustomTheme();
String themeCSS = (String) theme.getProperty("theme");
model.addAttribute("selectedTheme", theme.getName());
model.addAttribute("customTheme", StringUtils.isBlank(themeCSS) ? utils.getDefaultTheme() : themeCSS);
return "base";
}
@PostMapping("/add-space")
public String addSpace(@RequestParam String space, HttpServletRequest req, HttpServletResponse res, Model model) {
Profile authUser = utils.getAuthUser(req);
if (!StringUtils.isBlank(space) && utils.isAdmin(authUser)) {
Sysprop spaceObj = utils.buildSpaceObject(space);
if (utils.isDefaultSpace(spaceObj.getId()) || pc.getCount("scooldspace") >= MAX_SPACES ||
pc.read(spaceObj.getId()) != null) {
if (utils.isAjaxRequest(req)) {
res.setStatus(400);
return "space";
} else {
return "redirect:" + ADMINLINK + "?code=7&error=true";
}
} else {
if (pc.create(spaceObj) != null) {
authUser.getSpaces().add(spaceObj.getId() + Para.getConfig().separator() + spaceObj.getName());
authUser.update();
model.addAttribute("space", spaceObj);
utils.getAllSpaces().add(spaceObj);
} else {
model.addAttribute("error", Collections.singletonMap("name", utils.getLang(req).get("posts.error1")));
}
}
} else {
model.addAttribute("error", Collections.singletonMap("name", utils.getLang(req).get("requiredfield")));
}
if (utils.isAjaxRequest(req)) {
res.setStatus(model.containsAttribute("error") ? 400 : 200);
return "space";
} else {
return "redirect:" + ADMINLINK;
}
}
@PostMapping("/remove-space")
public String removeSpace(@RequestParam String space, HttpServletRequest req, HttpServletResponse res) {
Profile authUser = utils.getAuthUser(req);
if (!StringUtils.isBlank(space) && utils.isAdmin(authUser)) {
Sysprop s = new Sysprop(utils.getSpaceId(space));
pc.delete(s);
authUser.getSpaces().remove(space);
authUser.update();
utils.getAllSpaces().remove(s);
}
if (utils.isAjaxRequest(req)) {
res.setStatus(200);
return "space";
} else {
return "redirect:" + ADMINLINK;
}
}
@PostMapping("/rename-space")
public String renameSpace(@RequestParam String space, @RequestParam String newspace,
HttpServletRequest req, HttpServletResponse res) {
Profile authUser = utils.getAuthUser(req);
Sysprop s = pc.read(utils.getSpaceId(space));
if (s != null && utils.isAdmin(authUser)) {
String origSpace = s.getId() + Para.getConfig().separator() + s.getName();
int index = utils.getAllSpaces().indexOf(s);
s.setName(newspace);
pc.update(s);
if (index >= 0) {
utils.getAllSpaces().get(index).setName(newspace);
}
Pager pager = new Pager(1, "_docid", false, CONF.maxItemsPerPage());
LinkedList<Map<String, Object>> toUpdate = new LinkedList<>();
List<Profile> profiles;
do {
String query = "properties.spaces:(\"" + origSpace + "\")";
profiles = pc.findQuery(Utils.type(Profile.class), query, pager);
profiles.stream().forEach(p -> {
p.getSpaces().remove(origSpace);
p.getSpaces().add(s.getId() + Para.getConfig().separator() + s.getName());
Map<String, Object> profile = new HashMap<>();
profile.put(Config._ID, p.getId());
profile.put("spaces", p.getSpaces());
toUpdate.add(profile);
});
if (!toUpdate.isEmpty()) {
pc.invokePatch("_batch", toUpdate, Map.class);
}
} while (!profiles.isEmpty());
}
if (utils.isAjaxRequest(req)) {
res.setStatus(200);
return "space";
} else {
return "redirect:" + ADMINLINK;
}
}
@PostMapping("/create-webhook")
public String createWebhook(@RequestParam String targetUrl, @RequestParam(required = false) String type,
@RequestParam Boolean json, @RequestParam Set<String> events, HttpServletRequest req, Model model) {
Profile authUser = utils.getAuthUser(req);
if (Utils.isValidURL(targetUrl) && utils.isAdmin(authUser) && utils.isWebhooksEnabled()) {
Webhook webhook = new Webhook(targetUrl);
webhook.setCreate(events.contains("create"));
webhook.setUpdate(events.contains("update"));
webhook.setDelete(events.contains("delete"));
webhook.setCreateAll(events.contains("createAll"));
webhook.setUpdateAll(events.contains("updateAll"));
webhook.setDeleteAll(events.contains("deleteAll"));
webhook.setCustomEvents(events.stream().filter(e -> !StringUtils.equalsAny(e,
"create", "update", "delete", "createAll", "updateAll", "deleteAll")).collect(Collectors.toList()));
if (utils.getCoreScooldTypes().contains(type)) {
webhook.setTypeFilter(type);
}
webhook.setUrlEncoded(!json);
webhook.resetSecret();
pc.create(webhook);
} else {
model.addAttribute("error", Collections.singletonMap("targetUrl", utils.getLang(req).get("requiredfield")));
return "base";
}
return "redirect:" + ADMINLINK + "#webhooks-tab";
}
@PostMapping("/toggle-webhook")
public String toggleWebhook(@RequestParam String id, HttpServletRequest req, HttpServletResponse res) {
Profile authUser = utils.getAuthUser(req);
if (!StringUtils.isBlank(id) && utils.isAdmin(authUser) && utils.isWebhooksEnabled()) {
Webhook webhook = pc.read(id);
if (webhook != null) {
webhook.setActive(!webhook.getActive());
pc.update(webhook);
}
}
if (utils.isAjaxRequest(req)) {
res.setStatus(200);
return "base";
} else {
return "redirect:" + ADMINLINK + "#webhooks-tab";
}
}
@PostMapping("/delete-webhook")
public String deleteWebhook(@RequestParam String id, HttpServletRequest req, HttpServletResponse res) {
Profile authUser = utils.getAuthUser(req);
if (!StringUtils.isBlank(id) && utils.isAdmin(authUser) && utils.isWebhooksEnabled()) {
Webhook webhook = new Webhook();
webhook.setId(id);
pc.delete(webhook);
}
if (utils.isAjaxRequest(req)) {
res.setStatus(200);
return "base";
} else {
return "redirect:" + ADMINLINK + "#webhooks-tab";
}
}
@PostMapping
public String forceDelete(@RequestParam Boolean confirmdelete, @RequestParam String id, HttpServletRequest req) {
Profile authUser = utils.getAuthUser(req);
if (confirmdelete && utils.isAdmin(authUser)) {
ParaObject object = pc.read(id);
if (object != null) {
object.delete();
logger.info("{} #{} deleted {} #{}", authUser.getName(), authUser.getId(),
object.getClass().getName(), object.getId());
}
}
return "redirect:" + Optional.ofNullable(req.getParameter("returnto")).orElse(ADMINLINK);
}
@GetMapping(value = "/export", produces = "application/zip")
public ResponseEntity<StreamingResponseBody> backup(HttpServletRequest req, HttpServletResponse response) {
Profile authUser = utils.getAuthUser(req);
if (!utils.isAdmin(authUser)) {
return new ResponseEntity<StreamingResponseBody>(HttpStatus.UNAUTHORIZED);
}
String fileName = App.identifier(CONF.paraAccessKey()) + "_" + Utils.formatDate("YYYYMMdd_HHmmss", Locale.US);
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".zip");
return new ResponseEntity<StreamingResponseBody>(out -> {
// export all fields, even those which are JSON-ignored
ObjectWriter writer = JsonMapper.builder().disable(MapperFeature.USE_ANNOTATIONS).build().writer().
without(SerializationFeature.INDENT_OUTPUT).
without(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
long count = 0;
int partNum = 0;
// find all objects even if there are more than 10000 users in the system
Pager pager = new Pager(1, "_docid", false, CONF.maxItemsPerPage());
List<ParaObject> objects;
do {
objects = pc.findQuery("", "*", pager);
ZipEntry zipEntry = new ZipEntry(fileName + "_part" + (++partNum) + ".json");
zipOut.putNextEntry(zipEntry);
writer.writeValue(zipOut, objects);
count += objects.size();
} while (!objects.isEmpty());
logger.info("Exported {} objects to {}. Downloaded by {} (pager.count={})", count, fileName + ".zip",
authUser.getCreatorid() + " " + authUser.getName(), pager.getCount());
} catch (final IOException e) {
logger.error("Failed to export data.", e);
}
}, HttpStatus.OK);
}
@PostMapping("/import")
public String restore(@RequestParam("file") MultipartFile file,
@RequestParam(required = false, defaultValue = "false") Boolean isso,
HttpServletRequest req, HttpServletResponse res) {
Profile authUser = utils.getAuthUser(req);
if (!utils.isAdmin(authUser)) {
res.setStatus(403);
return null;
}
ObjectReader reader = ParaObjectUtils.getJsonMapper().readerFor(new TypeReference<List<Map<String, Object>>>() { });
String filename = file.getOriginalFilename();
Sysprop s = new Sysprop();
s.setType("scooldimport");
s.setCreatorid(authUser.getCreatorid());
s.setName(authUser.getName());
s.addProperty("status", "pending");
s.addProperty("count", 0);
s.addProperty("file", filename);
Sysprop si = pc.create(s);
Para.asyncExecute(() -> {
Map<String, String> comments2authors = new LinkedHashMap<>();
Map<String, User> accounts2emails = new LinkedHashMap<>();
try (InputStream inputStream = file.getInputStream()) {
if (StringUtils.endsWithIgnoreCase(filename, ".zip")) {
try (ZipInputStream zipIn = new ZipInputStream(inputStream)) {
ZipEntry zipEntry;
List<ParaObject> toCreate = new LinkedList<ParaObject>();
long countUpdated = Utils.timestamp();
while ((zipEntry = zipIn.getNextEntry()) != null) {
if (isso) {
importFromSOArchive(zipIn, zipEntry, reader, comments2authors, accounts2emails, si);
} else if (zipEntry.getName().endsWith(".json")) {
List<Map<String, Object>> objects = reader.readValue(new FilterInputStream(zipIn) {
public void close() throws IOException {
zipIn.closeEntry();
}
});
objects.forEach(o -> toCreate.add(ParaObjectUtils.setAnnotatedFields(o)));
if (toCreate.size() >= CONF.importBatchSize()) {
pc.createAll(toCreate);
toCreate.clear();
}
si.addProperty("count", ((int) si.getProperty("count")) + objects.size());
} else {
logger.error("Expected JSON but found unknown file type to import: {}", zipEntry.getName());
}
if (Utils.timestamp() > countUpdated + TimeUnit.SECONDS.toMillis(5)) {
pc.update(si);
countUpdated = Utils.timestamp();
}
}
if (!toCreate.isEmpty()) {
pc.createAll(toCreate);
}
if (isso) {
// apply additional fixes to data
updateSOCommentAuthors(comments2authors);
updateSOUserAccounts(accounts2emails);
}
}
} else if (StringUtils.endsWithIgnoreCase(filename, ".json")) {
List<Map<String, Object>> objects = reader.readValue(inputStream);
List<ParaObject> toCreate = new LinkedList<ParaObject>();
objects.forEach(o -> toCreate.add(ParaObjectUtils.setAnnotatedFields(o)));
si.addProperty("count", objects.size());
pc.createAll(toCreate);
}
logger.info("Imported {} objects to {}. Executed by {}", si.getProperty("count"),
CONF.paraAccessKey(), authUser.getCreatorid() + " " + authUser.getName());
si.addProperty("status", "done");
} catch (Exception e) {
logger.error("Failed to import " + filename, e);
si.addProperty("status", "failed");
} finally {
pc.update(si);
}
});
//return "redirect:" + ADMINLINK + "?error=true&imported=" + count;
return "redirect:" + ADMINLINK + "?success=true&imported=1#backup-tab";
}
@PostMapping("/set-theme")
public String setTheme(@RequestParam String theme, @RequestParam String css, HttpServletRequest req) {
Profile authUser = utils.getAuthUser(req);
if (utils.isAdmin(authUser)) {
utils.setCustomTheme(Utils.stripAndTrim(theme, "", true), css);
}
return "redirect:" + ADMINLINK + "#themes-tab";
}
@ResponseBody
@PostMapping(path = "/generate-api-key", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> generateAPIKey(@RequestParam Integer validityHours,
HttpServletRequest req, Model model) throws ParseException {
Profile authUser = utils.getAuthUser(req);
if (utils.isAdmin(authUser)) {
String jti = UUID.randomUUID().toString();
Map<String, Object> claims = Collections.singletonMap("jti", jti);
SignedJWT jwt = utils.generateJWToken(claims, TimeUnit.HOURS.toSeconds(validityHours));
if (jwt != null) {
String jwtString = jwt.serialize();
Date exp = jwt.getJWTClaimsSet().getExpirationTime();
utils.registerApiKey(jti, jwtString);
Map<String, Object> data = new HashMap<String, Object>();
data.put("jti", jti);
data.put("jwt", jwtString);
data.put("exp", exp == null ? 0L : Utils.formatDate(exp.getTime(), "YYYY-MM-dd HH:mm", Locale.UK));
return ResponseEntity.ok().body(data);
}
}
return ResponseEntity.status(403).build();
}
@ResponseBody
@PostMapping(path = "/revoke-api-key", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> revokeAPIKey(@RequestParam String jti, HttpServletRequest req, Model model) {
Profile authUser = utils.getAuthUser(req);
if (utils.isAdmin(authUser)) {
utils.revokeApiKey(jti);
return ResponseEntity.ok().build();
}
return ResponseEntity.status(403).build();
}
@PostMapping("/reindex")
public String reindex(HttpServletRequest req, Model model) {
if (utils.isAdmin(utils.getAuthUser(req))) {
Para.asyncExecute(() -> pc.rebuildIndex());
logger.info("Started rebuilding the search index for '{}'...", CONF.paraAccessKey());
}
return "redirect:" + ADMINLINK;
}
private List<ParaObject> importFromSOArchive(ZipInputStream zipIn, ZipEntry zipEntry, ObjectReader mapReader,
Map<String, String> comments2authors, Map<String, User> accounts2emails, Sysprop si)
throws IOException, ParseException {
if (zipEntry.getName().endsWith(".json")) {
List<Map<String, Object>> objs = mapReader.readValue(new FilterInputStream(zipIn) {
public void close() throws IOException {
zipIn.closeEntry();
}
});
List<ParaObject> toImport = new LinkedList<>();
switch (zipEntry.getName()) {
case "posts.json":
importPostsFromSO(objs, toImport, si);
break;
case "tags.json":
importTagsFromSO(objs, toImport, si);
break;
case "comments.json":
importCommentsFromSO(objs, toImport, comments2authors, si);
break;
case "users.json":
importUsersFromSO(objs, toImport, accounts2emails, si);
break;
case "users2badges.json":
// nice to have...
break;
case "accounts.json":
importAccountsFromSO(objs, accounts2emails);
break;
default:
break;
}
// IN PRO: rewrite all image links to relative local URLs
return toImport;
} else {
// IN PRO: store files in ./uploads
return Collections.emptyList();
}
}
private void importPostsFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport, Sysprop si)
throws ParseException {
logger.info("Importing {} posts...", objs.size());
int imported = 0;
for (Map<String, Object> obj : objs) {
Post p;
if (StringUtils.equalsAnyIgnoreCase((String) obj.get("postType"), "question", "article")) {
p = new Question();
p.setTitle((String) obj.get("title"));
String t = StringUtils.stripStart(StringUtils.stripEnd((String) obj.
getOrDefault("tags", ""), "|"), "|");
p.setTags(Arrays.asList(t.split("\\|")));
p.setAnswercount(((Integer) obj.getOrDefault("answerCount", 0)).longValue());
Integer answerId = (Integer) obj.getOrDefault("acceptedAnswerId", null);
p.setAnswerid(answerId != null ? "post_" + answerId : null);
} else if ("answer".equalsIgnoreCase((String) obj.get("postType"))) {
p = new Reply();
Integer parentId = (Integer) obj.getOrDefault("parentId", null);
p.setParentid(parentId != null ? "post_" + parentId : null);
} else {
continue;
}
p.setId("post_" + (Integer) obj.getOrDefault("id", Utils.getNewId()));
p.setBody((String) obj.get("bodyMarkdown"));
p.setVotes((Integer) obj.getOrDefault("score", 0));
p.setTimestamp(DateUtils.parseDate((String) obj.get("creationDate"), soDateFormat1, soDateFormat2).getTime());
Integer creatorId = (Integer) obj.getOrDefault("ownerUserId", null);
if (creatorId == null || creatorId == -1) {
p.setCreatorid(utils.getSystemUser().getId());
} else {
p.setCreatorid(Profile.id("user_" + creatorId)); // add prefix to avoid conflicts
}
toImport.add(p);
imported++;
if (toImport.size() >= CONF.importBatchSize()) {
pc.createAll(toImport);
toImport.clear();
}
}
if (!toImport.isEmpty()) {
pc.createAll(toImport);
toImport.clear();
}
si.addProperty("count", ((int) si.getProperty("count")) + imported);
}
private void importTagsFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport, Sysprop si) {
logger.info("Importing {} tags...", objs.size());
int imported = 0;
for (Map<String, Object> obj : objs) {
Tag t = new Tag((String) obj.get("name"));
t.setCount((Integer) obj.getOrDefault("count", 0));
toImport.add(t);
imported++;
if (toImport.size() >= CONF.importBatchSize()) {
pc.createAll(toImport);
toImport.clear();
}
}
if (!toImport.isEmpty()) {
pc.createAll(toImport);
toImport.clear();
}
si.addProperty("count", ((int) si.getProperty("count")) + imported);
}
private void importCommentsFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport,
Map<String, String> comments2authors, Sysprop si) throws ParseException {
logger.info("Importing {} comments...", objs.size());
int imported = 0;
for (Map<String, Object> obj : objs) {
Comment c = new Comment();
c.setId("comment_" + (Integer) obj.get("id"));
c.setComment((String) obj.get("text"));
Integer parentId = (Integer) obj.getOrDefault("postId", null);
c.setParentid(parentId != null ? "post_" + parentId : null);
c.setTimestamp(DateUtils.parseDate((String) obj.get("creationDate"), soDateFormat1, soDateFormat2).getTime());
Integer creatorId = (Integer) obj.getOrDefault("userId", null);
String userid = "user_" + creatorId;
c.setCreatorid(creatorId != null ? Profile.id(userid) : utils.getSystemUser().getId());
comments2authors.put(c.getId(), userid);
toImport.add(c);
imported++;
if (toImport.size() >= CONF.importBatchSize()) {
pc.createAll(toImport);
toImport.clear();
}
}
if (!toImport.isEmpty()) {
pc.createAll(toImport);
toImport.clear();
}
si.addProperty("count", ((int) si.getProperty("count")) + imported);
}
private void importUsersFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport,
Map<String, User> accounts2emails, Sysprop si) throws ParseException {
logger.info("Importing {} users...", objs.size());
int imported = 0;
for (Map<String, Object> obj : objs) {
User u = new User();
u.setId("user_" + (Integer) obj.get("id"));
u.setTimestamp(DateUtils.parseDate((String) obj.get("creationDate"), soDateFormat1, soDateFormat2).getTime());
u.setActive(true);
u.setCreatorid(((Integer) obj.get("accountId")).toString());
u.setGroups("admin".equalsIgnoreCase((String) obj.get("userTypeId"))
? User.Groups.ADMINS.toString() : User.Groups.USERS.toString());
u.setEmail(u.getId() + "@scoold.com");
u.setIdentifier(u.getEmail());
u.setName((String) obj.get("realName"));
String lastLogin = (String) obj.get("lastLoginDate");
u.setUpdated(StringUtils.isBlank(lastLogin) ? null :
DateUtils.parseDate(lastLogin, soDateFormat1, soDateFormat2).getTime());
u.setPicture((String) obj.get("profileImageUrl"));
u.setPassword(Utils.generateSecurityToken(10));
Profile p = Profile.fromUser(u);
p.setVotes((Integer) obj.get("reputation"));
p.setAboutme((String) obj.getOrDefault("title", ""));
p.setLastseen(u.getUpdated());
toImport.add(u);
toImport.add(p);
imported += 2;
User cachedUser = accounts2emails.get(u.getCreatorid());
if (cachedUser == null) {
User cu = new User(u.getId());
accounts2emails.put(u.getCreatorid(), cu);
} else {
cachedUser.setId(u.getId());
}
if (toImport.size() >= CONF.importBatchSize()) {
pc.createAll(toImport);
toImport.clear();
}
}
if (!toImport.isEmpty()) {
pc.createAll(toImport);
toImport.clear();
}
si.addProperty("count", ((int) si.getProperty("count")) + imported);
}
private void importAccountsFromSO(List<Map<String, Object>> objs, Map<String, User> accounts2emails) {
logger.info("Importing {} accounts...", objs.size());
for (Map<String, Object> obj : objs) {
String accountId = ((Integer) obj.get("accountId")).toString();
String email = (String) obj.get("verifiedEmail");
User cachedUser = accounts2emails.get(accountId);
if (cachedUser == null) {
User cu = new User();
cu.setEmail(email);
cu.setIdentifier(email);
accounts2emails.put(accountId, cu);
} else {
cachedUser.setEmail(email);
cachedUser.setIdentifier(email);
}
}
}
private void updateSOCommentAuthors(Map<String, String> comments2authors) {
if (!comments2authors.isEmpty()) {
// fetch & update comment author names
Map<String, ParaObject> authors = pc.readAll(new ArrayList<>(comments2authors.values())).stream().
collect(Collectors.toMap(k -> k.getId(), v -> v));
List<Map<String, String>> toPatch = new LinkedList<>();
for (Map.Entry<String, String> entry : comments2authors.entrySet()) {
Map<String, String> user = new HashMap<>();
user.put(Config._ID, entry.getKey());
if (authors.containsKey(entry.getValue())) {
user.put("authorName", authors.get(entry.getValue()).getName());
}
toPatch.add(user);
if (toPatch.size() >= CONF.importBatchSize()) {
pc.invokePatch("_batch", toPatch, Map.class);
toPatch.clear();
}
}
if (!toPatch.isEmpty()) {
pc.invokePatch("_batch", toPatch, Map.class);
toPatch.clear();
}
}
}
private void updateSOUserAccounts(Map<String, User> accounts2emails) {
List<Map<String, String>> toPatch = new LinkedList<>();
for (Map.Entry<String, User> entry : accounts2emails.entrySet()) {
User u = entry.getValue();
Map<String, String> user = new HashMap<>();
user.put(Config._ID, u.getId());
user.put(Config._EMAIL, u.getEmail());
user.put(Config._IDENTIFIER, u.getEmail());
toPatch.add(user);
if (toPatch.size() >= CONF.importBatchSize()) {
pc.invokePatch("_batch", toPatch, Map.class);
toPatch.clear();
}
}
if (!toPatch.isEmpty()) {
pc.invokePatch("_batch", toPatch, Map.class);
toPatch.clear();
}
}
}
| src/main/java/com/erudika/scoold/controllers/AdminController.java | /*
* Copyright 2013-2022 Erudika. https://erudika.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 issues and patches go to: https://github.com/erudika
*/
package com.erudika.scoold.controllers;
import com.erudika.para.client.ParaClient;
import com.erudika.para.core.App;
import com.erudika.para.core.ParaObject;
import com.erudika.para.core.Sysprop;
import com.erudika.para.core.Tag;
import com.erudika.para.core.User;
import com.erudika.para.core.Webhook;
import com.erudika.para.core.utils.Config;
import com.erudika.para.core.utils.Pager;
import com.erudika.para.core.utils.Para;
import com.erudika.para.core.utils.ParaObjectUtils;
import com.erudika.para.core.utils.Utils;
import com.erudika.scoold.ScooldConfig;
import static com.erudika.scoold.ScooldServer.ADMINLINK;
import static com.erudika.scoold.ScooldServer.HOMEPAGE;
import static com.erudika.scoold.ScooldServer.SIGNINLINK;
import com.erudika.scoold.core.Comment;
import com.erudika.scoold.core.Post;
import com.erudika.scoold.core.Profile;
import com.erudika.scoold.core.Question;
import com.erudika.scoold.core.Reply;
import com.erudika.scoold.utils.ScooldUtils;
import com.erudika.scoold.utils.Version;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.nimbusds.jwt.SignedJWT;
import com.typesafe.config.ConfigValue;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
/**
*
* @author Alex Bogdanovski [[email protected]]
*/
@Controller
@RequestMapping("/admin")
public class AdminController {
private static final Logger logger = LoggerFactory.getLogger(AdminController.class);
private static final ScooldConfig CONF = ScooldUtils.getConfig();
private static final int MAX_SPACES = 10; // Hey! It's cool to edit this, but please consider buying Scoold Pro! :)
private final String soDateFormat1 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private final String soDateFormat2 = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private final ScooldUtils utils;
private final ParaClient pc;
@Inject
public AdminController(ScooldUtils utils) {
this.utils = utils;
this.pc = utils.getParaClient();
}
@GetMapping
public String get(HttpServletRequest req, Model model) {
if (utils.isAuthenticated(req) && !utils.isAdmin(utils.getAuthUser(req))) {
return "redirect:" + HOMEPAGE;
} else if (!utils.isAuthenticated(req)) {
return "redirect:" + SIGNINLINK + "?returnto=" + ADMINLINK;
}
Map<String, Object> configMap = new LinkedHashMap<String, Object>();
for (Map.Entry<String, ConfigValue> entry : CONF.getConfig().entrySet()) {
ConfigValue value = entry.getValue();
configMap.put(entry.getKey(), value != null ? value.unwrapped() : "-");
}
Pager itemcount = utils.getPager("page", req);
Pager itemcount1 = utils.getPager("page1", req);
itemcount.setLimit(40);
model.addAttribute("path", "admin.vm");
model.addAttribute("title", utils.getLang(req).get("administration.title"));
model.addAttribute("configMap", configMap);
model.addAttribute("version", pc.getServerVersion());
model.addAttribute("endpoint", CONF.redirectUri());
model.addAttribute("paraapp", CONF.paraAccessKey());
model.addAttribute("spaces", pc.findQuery("scooldspace", "*", itemcount));
model.addAttribute("webhooks", pc.findQuery(Utils.type(Webhook.class), "*", itemcount1));
model.addAttribute("scooldimports", pc.findQuery("scooldimport", "*", new Pager(7)));
model.addAttribute("coreScooldTypes", utils.getCoreScooldTypes());
model.addAttribute("customHookEvents", utils.getCustomHookEvents());
model.addAttribute("apiKeys", utils.getApiKeys());
model.addAttribute("apiKeysExpirations", utils.getApiKeysExpirations());
model.addAttribute("itemcount", itemcount);
model.addAttribute("itemcount1", itemcount1);
model.addAttribute("isDefaultSpacePublic", utils.isDefaultSpacePublic());
model.addAttribute("scooldVersion", Version.getVersion());
model.addAttribute("scooldRevision", Version.getRevision());
String importedCount = req.getParameter("imported");
if (importedCount != null) {
if (req.getParameter("success") != null) {
model.addAttribute("infoStripMsg", "Started a new data import task. ");
} else {
model.addAttribute("infoStripMsg", "Data import task failed! The archive was partially imported.");
}
}
Sysprop theme = utils.getCustomTheme();
String themeCSS = (String) theme.getProperty("theme");
model.addAttribute("selectedTheme", theme.getName());
model.addAttribute("customTheme", StringUtils.isBlank(themeCSS) ? utils.getDefaultTheme() : themeCSS);
return "base";
}
@PostMapping("/add-space")
public String addSpace(@RequestParam String space, HttpServletRequest req, HttpServletResponse res, Model model) {
Profile authUser = utils.getAuthUser(req);
if (!StringUtils.isBlank(space) && utils.isAdmin(authUser)) {
Sysprop spaceObj = utils.buildSpaceObject(space);
if (utils.isDefaultSpace(spaceObj.getId()) || pc.getCount("scooldspace") >= MAX_SPACES ||
pc.read(spaceObj.getId()) != null) {
if (utils.isAjaxRequest(req)) {
res.setStatus(400);
return "space";
} else {
return "redirect:" + ADMINLINK + "?code=7&error=true";
}
} else {
if (pc.create(spaceObj) != null) {
authUser.getSpaces().add(spaceObj.getId() + Para.getConfig().separator() + spaceObj.getName());
authUser.update();
model.addAttribute("space", spaceObj);
utils.getAllSpaces().add(spaceObj);
} else {
model.addAttribute("error", Collections.singletonMap("name", utils.getLang(req).get("posts.error1")));
}
}
} else {
model.addAttribute("error", Collections.singletonMap("name", utils.getLang(req).get("requiredfield")));
}
if (utils.isAjaxRequest(req)) {
res.setStatus(model.containsAttribute("error") ? 400 : 200);
return "space";
} else {
return "redirect:" + ADMINLINK;
}
}
@PostMapping("/remove-space")
public String removeSpace(@RequestParam String space, HttpServletRequest req, HttpServletResponse res) {
Profile authUser = utils.getAuthUser(req);
if (!StringUtils.isBlank(space) && utils.isAdmin(authUser)) {
Sysprop s = new Sysprop(utils.getSpaceId(space));
pc.delete(s);
authUser.getSpaces().remove(space);
authUser.update();
utils.getAllSpaces().remove(s);
}
if (utils.isAjaxRequest(req)) {
res.setStatus(200);
return "space";
} else {
return "redirect:" + ADMINLINK;
}
}
@PostMapping("/rename-space")
public String renameSpace(@RequestParam String space, @RequestParam String newspace,
HttpServletRequest req, HttpServletResponse res) {
Profile authUser = utils.getAuthUser(req);
Sysprop s = pc.read(utils.getSpaceId(space));
if (s != null && utils.isAdmin(authUser)) {
String origSpace = s.getId() + Para.getConfig().separator() + s.getName();
int index = utils.getAllSpaces().indexOf(s);
s.setName(newspace);
pc.update(s);
if (index >= 0) {
utils.getAllSpaces().get(index).setName(newspace);
}
Pager pager = new Pager(1, "_docid", false, CONF.maxItemsPerPage());
LinkedList<Map<String, Object>> toUpdate = new LinkedList<>();
List<Profile> profiles;
do {
String query = "properties.spaces:(\"" + origSpace + "\")";
profiles = pc.findQuery(Utils.type(Profile.class), query, pager);
profiles.stream().forEach(p -> {
p.getSpaces().remove(origSpace);
p.getSpaces().add(s.getId() + Para.getConfig().separator() + s.getName());
Map<String, Object> profile = new HashMap<>();
profile.put(Config._ID, p.getId());
profile.put("spaces", p.getSpaces());
toUpdate.add(profile);
});
if (!toUpdate.isEmpty()) {
pc.invokePatch("_batch", toUpdate, Map.class);
}
} while (!profiles.isEmpty());
}
if (utils.isAjaxRequest(req)) {
res.setStatus(200);
return "space";
} else {
return "redirect:" + ADMINLINK;
}
}
@PostMapping("/create-webhook")
public String createWebhook(@RequestParam String targetUrl, @RequestParam(required = false) String type,
@RequestParam Boolean json, @RequestParam Set<String> events, HttpServletRequest req, Model model) {
Profile authUser = utils.getAuthUser(req);
if (Utils.isValidURL(targetUrl) && utils.isAdmin(authUser) && utils.isWebhooksEnabled()) {
Webhook webhook = new Webhook(targetUrl);
webhook.setCreate(events.contains("create"));
webhook.setUpdate(events.contains("update"));
webhook.setDelete(events.contains("delete"));
webhook.setCreateAll(events.contains("createAll"));
webhook.setUpdateAll(events.contains("updateAll"));
webhook.setDeleteAll(events.contains("deleteAll"));
webhook.setCustomEvents(events.stream().filter(e -> !StringUtils.equalsAny(e,
"create", "update", "delete", "createAll", "updateAll", "deleteAll")).collect(Collectors.toList()));
if (utils.getCoreScooldTypes().contains(type)) {
webhook.setTypeFilter(type);
}
webhook.setUrlEncoded(!json);
webhook.resetSecret();
pc.create(webhook);
} else {
model.addAttribute("error", Collections.singletonMap("targetUrl", utils.getLang(req).get("requiredfield")));
return "base";
}
return "redirect:" + ADMINLINK + "#webhooks-tab";
}
@PostMapping("/toggle-webhook")
public String toggleWebhook(@RequestParam String id, HttpServletRequest req, HttpServletResponse res) {
Profile authUser = utils.getAuthUser(req);
if (!StringUtils.isBlank(id) && utils.isAdmin(authUser) && utils.isWebhooksEnabled()) {
Webhook webhook = pc.read(id);
if (webhook != null) {
webhook.setActive(!webhook.getActive());
pc.update(webhook);
}
}
if (utils.isAjaxRequest(req)) {
res.setStatus(200);
return "base";
} else {
return "redirect:" + ADMINLINK + "#webhooks-tab";
}
}
@PostMapping("/delete-webhook")
public String deleteWebhook(@RequestParam String id, HttpServletRequest req, HttpServletResponse res) {
Profile authUser = utils.getAuthUser(req);
if (!StringUtils.isBlank(id) && utils.isAdmin(authUser) && utils.isWebhooksEnabled()) {
Webhook webhook = new Webhook();
webhook.setId(id);
pc.delete(webhook);
}
if (utils.isAjaxRequest(req)) {
res.setStatus(200);
return "base";
} else {
return "redirect:" + ADMINLINK + "#webhooks-tab";
}
}
@PostMapping
public String forceDelete(@RequestParam Boolean confirmdelete, @RequestParam String id, HttpServletRequest req) {
Profile authUser = utils.getAuthUser(req);
if (confirmdelete && utils.isAdmin(authUser)) {
ParaObject object = pc.read(id);
if (object != null) {
object.delete();
logger.info("{} #{} deleted {} #{}", authUser.getName(), authUser.getId(),
object.getClass().getName(), object.getId());
}
}
return "redirect:" + Optional.ofNullable(req.getParameter("returnto")).orElse(ADMINLINK);
}
@GetMapping(value = "/export", produces = "application/zip")
public ResponseEntity<StreamingResponseBody> backup(HttpServletRequest req, HttpServletResponse response) {
Profile authUser = utils.getAuthUser(req);
if (!utils.isAdmin(authUser)) {
return new ResponseEntity<StreamingResponseBody>(HttpStatus.UNAUTHORIZED);
}
String fileName = App.identifier(CONF.paraAccessKey()) + "_" + Utils.formatDate("YYYYMMdd_HHmmss", Locale.US);
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".zip");
return new ResponseEntity<StreamingResponseBody>(out -> {
// export all fields, even those which are JSON-ignored
ObjectWriter writer = JsonMapper.builder().disable(MapperFeature.USE_ANNOTATIONS).build().writer().
without(SerializationFeature.INDENT_OUTPUT).
without(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
long count = 0;
int partNum = 0;
// find all objects even if there are more than 10000 users in the system
Pager pager = new Pager(1, "_docid", false, CONF.maxItemsPerPage());
List<ParaObject> objects;
do {
objects = pc.findQuery("", "*", pager);
ZipEntry zipEntry = new ZipEntry(fileName + "_part" + (++partNum) + ".json");
zipOut.putNextEntry(zipEntry);
writer.writeValue(zipOut, objects);
count += objects.size();
} while (!objects.isEmpty());
logger.info("Exported {} objects to {}. Downloaded by {} (pager.count={})", count, fileName + ".zip",
authUser.getCreatorid() + " " + authUser.getName(), pager.getCount());
} catch (final IOException e) {
logger.error("Failed to export data.", e);
}
}, HttpStatus.OK);
}
@PostMapping("/import")
public String restore(@RequestParam("file") MultipartFile file,
@RequestParam(required = false, defaultValue = "false") Boolean isso,
HttpServletRequest req, HttpServletResponse res) {
Profile authUser = utils.getAuthUser(req);
if (!utils.isAdmin(authUser)) {
res.setStatus(403);
return null;
}
ObjectReader reader = ParaObjectUtils.getJsonMapper().readerFor(new TypeReference<List<Map<String, Object>>>() { });
String filename = file.getOriginalFilename();
Sysprop s = new Sysprop();
s.setType("scooldimport");
s.setCreatorid(authUser.getCreatorid());
s.setName(authUser.getName());
s.addProperty("status", "pending");
s.addProperty("count", 0);
s.addProperty("file", filename);
Sysprop si = pc.create(s);
Para.asyncExecute(() -> {
Map<String, String> comments2authors = new LinkedHashMap<>();
Map<String, String> accounts2emails = new LinkedHashMap<>();
try (InputStream inputStream = file.getInputStream()) {
if (StringUtils.endsWithIgnoreCase(filename, ".zip")) {
try (ZipInputStream zipIn = new ZipInputStream(inputStream)) {
ZipEntry zipEntry;
List<ParaObject> toCreate = new LinkedList<ParaObject>();
long countUpdated = Utils.timestamp();
while ((zipEntry = zipIn.getNextEntry()) != null) {
if (isso) {
importFromSOArchive(zipIn, zipEntry, reader, comments2authors, accounts2emails, si);
} else if (zipEntry.getName().endsWith(".json")) {
List<Map<String, Object>> objects = reader.readValue(new FilterInputStream(zipIn) {
public void close() throws IOException {
zipIn.closeEntry();
}
});
objects.forEach(o -> toCreate.add(ParaObjectUtils.setAnnotatedFields(o)));
if (toCreate.size() >= CONF.importBatchSize()) {
pc.createAll(toCreate);
toCreate.clear();
}
si.addProperty("count", ((int) si.getProperty("count")) + objects.size());
} else {
logger.error("Expected JSON but found unknown file type to import: {}", zipEntry.getName());
}
if (Utils.timestamp() > countUpdated + TimeUnit.SECONDS.toMillis(5)) {
pc.update(si);
countUpdated = Utils.timestamp();
}
}
if (!toCreate.isEmpty()) {
pc.createAll(toCreate);
}
if (isso) {
// apply additional fixes to data
updateSOCommentAuthors(comments2authors);
updateSOUserAccounts(accounts2emails);
}
}
} else if (StringUtils.endsWithIgnoreCase(filename, ".json")) {
List<Map<String, Object>> objects = reader.readValue(inputStream);
List<ParaObject> toCreate = new LinkedList<ParaObject>();
objects.forEach(o -> toCreate.add(ParaObjectUtils.setAnnotatedFields(o)));
si.addProperty("count", objects.size());
pc.createAll(toCreate);
}
logger.info("Imported {} objects to {}. Executed by {}", si.getProperty("count"),
CONF.paraAccessKey(), authUser.getCreatorid() + " " + authUser.getName());
si.addProperty("status", "done");
} catch (Exception e) {
logger.error("Failed to import " + filename, e);
si.addProperty("status", "failed");
} finally {
pc.update(si);
}
});
//return "redirect:" + ADMINLINK + "?error=true&imported=" + count;
return "redirect:" + ADMINLINK + "?success=true&imported=1#backup-tab";
}
@PostMapping("/set-theme")
public String setTheme(@RequestParam String theme, @RequestParam String css, HttpServletRequest req) {
Profile authUser = utils.getAuthUser(req);
if (utils.isAdmin(authUser)) {
utils.setCustomTheme(Utils.stripAndTrim(theme, "", true), css);
}
return "redirect:" + ADMINLINK + "#themes-tab";
}
@ResponseBody
@PostMapping(path = "/generate-api-key", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> generateAPIKey(@RequestParam Integer validityHours,
HttpServletRequest req, Model model) throws ParseException {
Profile authUser = utils.getAuthUser(req);
if (utils.isAdmin(authUser)) {
String jti = UUID.randomUUID().toString();
Map<String, Object> claims = Collections.singletonMap("jti", jti);
SignedJWT jwt = utils.generateJWToken(claims, TimeUnit.HOURS.toSeconds(validityHours));
if (jwt != null) {
String jwtString = jwt.serialize();
Date exp = jwt.getJWTClaimsSet().getExpirationTime();
utils.registerApiKey(jti, jwtString);
Map<String, Object> data = new HashMap<String, Object>();
data.put("jti", jti);
data.put("jwt", jwtString);
data.put("exp", exp == null ? 0L : Utils.formatDate(exp.getTime(), "YYYY-MM-dd HH:mm", Locale.UK));
return ResponseEntity.ok().body(data);
}
}
return ResponseEntity.status(403).build();
}
@ResponseBody
@PostMapping(path = "/revoke-api-key", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> revokeAPIKey(@RequestParam String jti, HttpServletRequest req, Model model) {
Profile authUser = utils.getAuthUser(req);
if (utils.isAdmin(authUser)) {
utils.revokeApiKey(jti);
return ResponseEntity.ok().build();
}
return ResponseEntity.status(403).build();
}
@PostMapping("/reindex")
public String reindex(HttpServletRequest req, Model model) {
if (utils.isAdmin(utils.getAuthUser(req))) {
Para.asyncExecute(() -> pc.rebuildIndex());
logger.info("Started rebuilding the search index for '{}'...", CONF.paraAccessKey());
}
return "redirect:" + ADMINLINK;
}
private List<ParaObject> importFromSOArchive(ZipInputStream zipIn, ZipEntry zipEntry, ObjectReader mapReader,
Map<String, String> comments2authors, Map<String, String> accounts2emails, Sysprop si)
throws IOException, ParseException {
if (zipEntry.getName().endsWith(".json")) {
List<Map<String, Object>> objs = mapReader.readValue(new FilterInputStream(zipIn) {
public void close() throws IOException {
zipIn.closeEntry();
}
});
List<ParaObject> toImport = new LinkedList<>();
switch (zipEntry.getName()) {
case "posts.json":
importPostsFromSO(objs, toImport, si);
break;
case "tags.json":
importTagsFromSO(objs, toImport, si);
break;
case "comments.json":
importCommentsFromSO(objs, toImport, comments2authors, si);
break;
case "users.json":
importUsersFromSO(objs, toImport, si);
break;
case "users2badges.json":
// nice to have...
break;
case "accounts.json":
importAccountsFromSO(objs, accounts2emails);
break;
default:
break;
}
// IN PRO: rewrite all image links to relative local URLs
return toImport;
} else {
// IN PRO: store files in ./uploads
return Collections.emptyList();
}
}
private void importPostsFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport, Sysprop si)
throws ParseException {
logger.info("Importing {} posts...", objs.size());
int imported = 0;
for (Map<String, Object> obj : objs) {
Post p;
if (StringUtils.equalsAnyIgnoreCase((String) obj.get("postType"), "question", "article")) {
p = new Question();
p.setTitle((String) obj.get("title"));
String t = StringUtils.stripStart(StringUtils.stripEnd((String) obj.
getOrDefault("tags", ""), "|"), "|");
p.setTags(Arrays.asList(t.split("\\|")));
p.setAnswercount(((Integer) obj.getOrDefault("answerCount", 0)).longValue());
Integer answerId = (Integer) obj.getOrDefault("acceptedAnswerId", null);
p.setAnswerid(answerId != null ? "post_" + answerId : null);
} else if ("answer".equalsIgnoreCase((String) obj.get("postType"))) {
p = new Reply();
Integer parentId = (Integer) obj.getOrDefault("parentId", null);
p.setParentid(parentId != null ? "post_" + parentId : null);
} else {
continue;
}
p.setId("post_" + (Integer) obj.getOrDefault("id", Utils.getNewId()));
p.setBody((String) obj.get("bodyMarkdown"));
p.setVotes((Integer) obj.getOrDefault("score", 0));
p.setTimestamp(DateUtils.parseDate((String) obj.get("creationDate"), soDateFormat1, soDateFormat2).getTime());
Integer creatorId = (Integer) obj.getOrDefault("ownerUserId", null);
if (creatorId == null || creatorId == -1) {
p.setCreatorid(utils.getSystemUser().getId());
} else {
p.setCreatorid(Profile.id("user_" + creatorId)); // add prefix to avoid conflicts
}
toImport.add(p);
imported++;
if (toImport.size() >= CONF.importBatchSize()) {
pc.createAll(toImport);
toImport.clear();
}
}
if (!toImport.isEmpty()) {
pc.createAll(toImport);
toImport.clear();
}
si.addProperty("count", ((int) si.getProperty("count")) + imported);
}
private void importTagsFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport, Sysprop si) {
logger.info("Importing {} tags...", objs.size());
int imported = 0;
for (Map<String, Object> obj : objs) {
Tag t = new Tag((String) obj.get("name"));
t.setCount((Integer) obj.getOrDefault("count", 0));
toImport.add(t);
imported++;
if (toImport.size() >= CONF.importBatchSize()) {
pc.createAll(toImport);
toImport.clear();
}
}
if (!toImport.isEmpty()) {
pc.createAll(toImport);
toImport.clear();
}
si.addProperty("count", ((int) si.getProperty("count")) + imported);
}
private void importCommentsFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport,
Map<String, String> comments2authors, Sysprop si) throws ParseException {
logger.info("Importing {} comments...", objs.size());
int imported = 0;
for (Map<String, Object> obj : objs) {
Comment c = new Comment();
c.setId("comment_" + (Integer) obj.get("id"));
c.setComment((String) obj.get("text"));
Integer parentId = (Integer) obj.getOrDefault("postId", null);
c.setParentid(parentId != null ? "post_" + parentId : null);
c.setTimestamp(DateUtils.parseDate((String) obj.get("creationDate"), soDateFormat1, soDateFormat2).getTime());
Integer creatorId = (Integer) obj.getOrDefault("userId", null);
String userid = "user_" + creatorId;
c.setCreatorid(creatorId != null ? Profile.id(userid) : utils.getSystemUser().getId());
comments2authors.put(c.getId(), userid);
toImport.add(c);
imported++;
if (toImport.size() >= CONF.importBatchSize()) {
pc.createAll(toImport);
toImport.clear();
}
}
if (!toImport.isEmpty()) {
pc.createAll(toImport);
toImport.clear();
}
si.addProperty("count", ((int) si.getProperty("count")) + imported);
}
private void importUsersFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport, Sysprop si)
throws ParseException {
logger.info("Importing {} users...", objs.size());
int imported = 0;
for (Map<String, Object> obj : objs) {
User u = new User();
u.setId("user_" + (Integer) obj.get("id"));
u.setTimestamp(DateUtils.parseDate((String) obj.get("creationDate"), soDateFormat1, soDateFormat2).getTime());
u.setActive(true);
u.setCreatorid(((Integer) obj.get("accountId")).toString());
u.setGroups("admin".equalsIgnoreCase((String) obj.get("userTypeId"))
? User.Groups.ADMINS.toString() : User.Groups.USERS.toString());
u.setEmail(u.getId() + "@scoold.com");
u.setIdentifier(u.getEmail());
u.setName((String) obj.get("realName"));
String lastLogin = (String) obj.get("lastLoginDate");
u.setUpdated(StringUtils.isBlank(lastLogin) ? null :
DateUtils.parseDate(lastLogin, soDateFormat1, soDateFormat2).getTime());
u.setPicture((String) obj.get("profileImageUrl"));
u.setPassword(Utils.generateSecurityToken(10));
Profile p = Profile.fromUser(u);
p.setVotes((Integer) obj.get("reputation"));
p.setAboutme((String) obj.getOrDefault("title", ""));
p.setLastseen(u.getUpdated());
toImport.add(u);
toImport.add(p);
imported += 2;
if (toImport.size() >= CONF.importBatchSize()) {
pc.createAll(toImport);
toImport.clear();
}
}
if (!toImport.isEmpty()) {
pc.createAll(toImport);
toImport.clear();
}
si.addProperty("count", ((int) si.getProperty("count")) + imported);
}
private void importAccountsFromSO(List<Map<String, Object>> objs, Map<String, String> accounts2emails) {
logger.info("Importing {} accounts...", objs.size());
for (Map<String, Object> obj : objs) {
accounts2emails.put(((Integer) obj.get("accountId")).toString(), (String) obj.get("verifiedEmail"));
}
}
private void updateSOCommentAuthors(Map<String, String> comments2authors) {
if (!comments2authors.isEmpty()) {
// fetch & update comment author names
Map<String, ParaObject> authors = pc.readAll(new ArrayList<>(comments2authors.values())).stream().
collect(Collectors.toMap(k -> k.getId(), v -> v));
List<Map<String, String>> toPatch = new LinkedList<>();
for (Map.Entry<String, String> entry : comments2authors.entrySet()) {
Map<String, String> user = new HashMap<>();
user.put(Config._ID, entry.getKey());
if (authors.containsKey(entry.getValue())) {
user.put("authorName", authors.get(entry.getValue()).getName());
}
toPatch.add(user);
if (toPatch.size() >= CONF.importBatchSize()) {
pc.invokePatch("_batch", toPatch, Map.class);
toPatch.clear();
}
}
if (!toPatch.isEmpty()) {
pc.invokePatch("_batch", toPatch, Map.class);
toPatch.clear();
}
}
}
private void updateSOUserAccounts(Map<String, String> accounts2emails) {
List<Map<String, String>> toPatch = new LinkedList<>();
// find all user objects even if there are more than 10000 users in the system
Pager pager = new Pager(1, "_docid", false, CONF.importBatchSize());
List<User> users;
do {
users = pc.findQuery(Utils.type(User.class), "*", pager);
if (!users.isEmpty()) {
users.stream().forEach(u -> {
if (accounts2emails.containsKey(u.getCreatorid())) {
u.setEmail(accounts2emails.get(u.getCreatorid()));
Map<String, String> user = new HashMap<>();
user.put(Config._ID, u.getId());
user.put(Config._EMAIL, u.getEmail());
user.put(Config._IDENTIFIER, u.getEmail());
toPatch.add(user);
}
});
}
pc.invokePatch("_batch", toPatch, Map.class);
toPatch.clear();
} while (!users.isEmpty());
}
}
| fixed bug which caused user duplication when importing data from SO
| src/main/java/com/erudika/scoold/controllers/AdminController.java | fixed bug which caused user duplication when importing data from SO | <ide><path>rc/main/java/com/erudika/scoold/controllers/AdminController.java
<ide>
<ide> Para.asyncExecute(() -> {
<ide> Map<String, String> comments2authors = new LinkedHashMap<>();
<del> Map<String, String> accounts2emails = new LinkedHashMap<>();
<add> Map<String, User> accounts2emails = new LinkedHashMap<>();
<ide> try (InputStream inputStream = file.getInputStream()) {
<ide> if (StringUtils.endsWithIgnoreCase(filename, ".zip")) {
<ide> try (ZipInputStream zipIn = new ZipInputStream(inputStream)) {
<ide> }
<ide>
<ide> private List<ParaObject> importFromSOArchive(ZipInputStream zipIn, ZipEntry zipEntry, ObjectReader mapReader,
<del> Map<String, String> comments2authors, Map<String, String> accounts2emails, Sysprop si)
<add> Map<String, String> comments2authors, Map<String, User> accounts2emails, Sysprop si)
<ide> throws IOException, ParseException {
<ide> if (zipEntry.getName().endsWith(".json")) {
<ide> List<Map<String, Object>> objs = mapReader.readValue(new FilterInputStream(zipIn) {
<ide> importCommentsFromSO(objs, toImport, comments2authors, si);
<ide> break;
<ide> case "users.json":
<del> importUsersFromSO(objs, toImport, si);
<add> importUsersFromSO(objs, toImport, accounts2emails, si);
<ide> break;
<ide> case "users2badges.json":
<ide> // nice to have...
<ide> si.addProperty("count", ((int) si.getProperty("count")) + imported);
<ide> }
<ide>
<del> private void importUsersFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport, Sysprop si)
<del> throws ParseException {
<add> private void importUsersFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport,
<add> Map<String, User> accounts2emails, Sysprop si) throws ParseException {
<ide> logger.info("Importing {} users...", objs.size());
<ide> int imported = 0;
<ide> for (Map<String, Object> obj : objs) {
<ide> toImport.add(u);
<ide> toImport.add(p);
<ide> imported += 2;
<add>
<add> User cachedUser = accounts2emails.get(u.getCreatorid());
<add> if (cachedUser == null) {
<add> User cu = new User(u.getId());
<add> accounts2emails.put(u.getCreatorid(), cu);
<add> } else {
<add> cachedUser.setId(u.getId());
<add> }
<add>
<ide> if (toImport.size() >= CONF.importBatchSize()) {
<ide> pc.createAll(toImport);
<ide> toImport.clear();
<ide> si.addProperty("count", ((int) si.getProperty("count")) + imported);
<ide> }
<ide>
<del> private void importAccountsFromSO(List<Map<String, Object>> objs, Map<String, String> accounts2emails) {
<add> private void importAccountsFromSO(List<Map<String, Object>> objs, Map<String, User> accounts2emails) {
<ide> logger.info("Importing {} accounts...", objs.size());
<ide> for (Map<String, Object> obj : objs) {
<del> accounts2emails.put(((Integer) obj.get("accountId")).toString(), (String) obj.get("verifiedEmail"));
<add> String accountId = ((Integer) obj.get("accountId")).toString();
<add> String email = (String) obj.get("verifiedEmail");
<add> User cachedUser = accounts2emails.get(accountId);
<add> if (cachedUser == null) {
<add> User cu = new User();
<add> cu.setEmail(email);
<add> cu.setIdentifier(email);
<add> accounts2emails.put(accountId, cu);
<add> } else {
<add> cachedUser.setEmail(email);
<add> cachedUser.setIdentifier(email);
<add> }
<ide> }
<ide> }
<ide>
<ide> }
<ide> }
<ide>
<del> private void updateSOUserAccounts(Map<String, String> accounts2emails) {
<add> private void updateSOUserAccounts(Map<String, User> accounts2emails) {
<ide> List<Map<String, String>> toPatch = new LinkedList<>();
<del> // find all user objects even if there are more than 10000 users in the system
<del> Pager pager = new Pager(1, "_docid", false, CONF.importBatchSize());
<del> List<User> users;
<del> do {
<del> users = pc.findQuery(Utils.type(User.class), "*", pager);
<del> if (!users.isEmpty()) {
<del> users.stream().forEach(u -> {
<del> if (accounts2emails.containsKey(u.getCreatorid())) {
<del> u.setEmail(accounts2emails.get(u.getCreatorid()));
<del> Map<String, String> user = new HashMap<>();
<del> user.put(Config._ID, u.getId());
<del> user.put(Config._EMAIL, u.getEmail());
<del> user.put(Config._IDENTIFIER, u.getEmail());
<del> toPatch.add(user);
<del> }
<del> });
<del> }
<add> for (Map.Entry<String, User> entry : accounts2emails.entrySet()) {
<add> User u = entry.getValue();
<add> Map<String, String> user = new HashMap<>();
<add> user.put(Config._ID, u.getId());
<add> user.put(Config._EMAIL, u.getEmail());
<add> user.put(Config._IDENTIFIER, u.getEmail());
<add> toPatch.add(user);
<add> if (toPatch.size() >= CONF.importBatchSize()) {
<add> pc.invokePatch("_batch", toPatch, Map.class);
<add> toPatch.clear();
<add> }
<add> }
<add> if (!toPatch.isEmpty()) {
<ide> pc.invokePatch("_batch", toPatch, Map.class);
<ide> toPatch.clear();
<del> } while (!users.isEmpty());
<add> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 9c34179642aba7aaa88a1d8851efec7e98ede431 | 0 | bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud | package com.planet_ink.coffee_mud.Libraries;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.CMLib.Library;
import com.planet_ink.coffee_mud.core.CMSecurity.DbgFlag;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.core.collections.MultiEnumeration.MultiEnumeratorBuilder;
import com.planet_ink.coffee_mud.core.interfaces.BoundedObject;
import com.planet_ink.coffee_mud.core.interfaces.BoundedObject.BoundedCube;
import com.planet_ink.coffee_mud.core.interfaces.LandTitle;
import com.planet_ink.coffee_mud.core.interfaces.MsgListener;
import com.planet_ink.coffee_mud.core.interfaces.PrivateProperty;
import com.planet_ink.coffee_mud.core.interfaces.SpaceObject;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.ShipDirectional.ShipDir;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.*;
import java.util.Map.Entry;
/*
Copyright 2001-2022 Bo Zimmerman
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.
*/
public class CMMap extends StdLibrary implements WorldMap
{
@Override
public String ID()
{
return "CMMap";
}
protected static MOB deityStandIn = null;
protected long lastVReset = 0;
protected CMNSortSVec<Area> areasList = new CMNSortSVec<Area>();
protected CMNSortSVec<Deity> deitiesList = new CMNSortSVec<Deity>();
protected List<Boardable> shipList = new SVector<Boardable>();
protected Map<String, Object> SCRIPT_HOST_SEMAPHORES = new Hashtable<String, Object>();
protected static final Comparator<Area> areaComparator = new Comparator<Area>()
{
@Override
public int compare(final Area o1, final Area o2)
{
if(o1==null)
return (o2==null)?0:-1;
return o1.Name().compareToIgnoreCase(o2.Name());
}
};
public Map<Integer,List<WeakReference<MsgListener>>>
globalHandlers = new SHashtable<Integer,List<WeakReference<MsgListener>>>();
public Map<String,SLinkedList<LocatedPair>>
scriptHostMap = new STreeMap<String,SLinkedList<LocatedPair>>();
private static final long EXPIRE_1MIN = 1*60*1000;
private static final long EXPIRE_5MINS = 5*60*1000;
private static final long EXPIRE_10MINS = 10*60*1000;
private static final long EXPIRE_20MINS = 20*60*1000;
private static final long EXPIRE_30MINS = 30*60*1000;
private static final long EXPIRE_1HOUR = 60*60*1000;
private static class LocatedPairImpl implements LocatedPair
{
final WeakReference<Room> roomW;
final WeakReference<PhysicalAgent> objW;
private LocatedPairImpl(final Room room, final PhysicalAgent host)
{
roomW = new WeakReference<Room>(room);
objW = new WeakReference<PhysicalAgent>(host);
}
@Override
public Room room()
{
return roomW.get();
}
@Override
public PhysicalAgent obj()
{
return objW.get();
}
}
private static Filterer<Area> mundaneAreaFilter=new Filterer<Area>()
{
@Override
public boolean passesFilter(final Area obj)
{
return !(obj instanceof SpaceObject);
}
};
private static Filterer<Area> topLevelAreaFilter=new Filterer<Area>()
{
@Override
public boolean passesFilter(final Area obj)
{
return ! obj.getParents().hasMoreElements();
}
};
protected int getGlobalIndex(final List<Environmental> list, final String name)
{
if(list.size()==0)
return -1;
int start=0;
int end=list.size()-1;
while(start<=end)
{
final int mid=(end+start)/2;
try
{
final int comp=list.get(mid).Name().compareToIgnoreCase(name);
if(comp==0)
return mid;
else
if(comp>0)
end=mid-1;
else
start=mid+1;
}
catch(final java.lang.ArrayIndexOutOfBoundsException e)
{
start=0;
end=list.size()-1;
}
}
return -1;
}
@Override
public void renamedArea(final Area theA)
{
areasList.reSort(theA);
}
// areas
@Override
public int numAreas()
{
return areasList.size();
}
@Override
public void addArea(final Area newOne)
{
areasList.add(newOne);
if((newOne instanceof SpaceObject)&&(!CMLib.space().isObjectInSpace((SpaceObject)newOne)))
CMLib.space().addObjectToSpace((SpaceObject)newOne);
}
@Override
public void delArea(final Area oneToDel)
{
areasList.remove(oneToDel);
if((oneToDel instanceof SpaceObject)&&(CMLib.space().isObjectInSpace((SpaceObject)oneToDel)))
CMLib.space().delObjectInSpace((SpaceObject)oneToDel);
Resources.removeResource("SYSTEM_AREA_FINDER_CACHE");
}
@Override
public Area getModelArea(final Area A)
{
if(A!=null)
{
if(CMath.bset(A.flags(),Area.FLAG_INSTANCE_CHILD))
{
final int x=A.Name().indexOf('_');
if((x>0)
&&(CMath.isInteger(A.Name().substring(0,x))))
{
final Area A2=getArea(A.Name().substring(x+1));
if(A2!=null)
return A2;
}
}
}
return A;
}
@Override
public Area getArea(final String calledThis)
{
final Map<String,Area> finder=getAreaFinder();
Area A=finder.get(calledThis.toLowerCase());
if((A!=null)&&(!A.amDestroyed()))
return A;
final SearchIDList<Area> list;
synchronized(areasList)
{
list = areasList;
}
A=list.find(calledThis);
if((A!=null)&&(!A.amDestroyed()))
{
if(!CMProps.getBoolVar(CMProps.Bool.MAPFINDSNOCACHE))
finder.put(calledThis.toLowerCase(), A);
return A;
}
return null;
}
@Override
public Area findAreaStartsWith(final String calledThis)
{
final boolean disableCaching=CMProps.getBoolVar(CMProps.Bool.MAPFINDSNOCACHE);
Area A=getArea(calledThis);
if(A!=null)
return A;
final Map<String,Area> finder=getAreaFinder();
A=finder.get(calledThis.toLowerCase());
if((A!=null)&&(!A.amDestroyed()))
return A;
for(final Enumeration<Area> a=areas();a.hasMoreElements();)
{
A=a.nextElement();
if(A.Name().toUpperCase().startsWith(calledThis))
{
if(!disableCaching)
finder.put(calledThis.toLowerCase(), A);
return A;
}
}
return null;
}
@Override
public Area findArea(final String calledThis)
{
final boolean disableCaching=CMProps.getBoolVar(CMProps.Bool.MAPFINDSNOCACHE);
Area A=findAreaStartsWith(calledThis);
if(A!=null)
return A;
final Map<String,Area> finder=getAreaFinder();
A=finder.get(calledThis.toLowerCase());
if((A!=null)&&(!A.amDestroyed()))
return A;
for(final Enumeration<Area> a=areas();a.hasMoreElements();)
{
A=a.nextElement();
if(CMLib.english().containsString(A.Name(),calledThis))
{
if(!disableCaching)
finder.put(calledThis.toLowerCase(), A);
return A;
}
}
return null;
}
@Override
public Enumeration<Area> areas()
{
return new IteratorEnumeration<Area>(areasList.iterator());
}
@Override
public Enumeration<Area> areasPlusShips()
{
final MultiEnumeration<Area> m=new MultiEnumeration<Area>(new IteratorEnumeration<Area>(areasList.iterator()));
m.addEnumeration(shipAreaEnumerator(null));
return m;
}
@Override
public Enumeration<Area> mundaneAreas()
{
return new FilteredEnumeration<Area>(areas(),mundaneAreaFilter);
}
@Override
public Enumeration<Area> topAreas()
{
return new FilteredEnumeration<Area>(areas(),topLevelAreaFilter);
}
@Override
public Enumeration<String> roomIDs()
{
return new Enumeration<String>()
{
private volatile Enumeration<String> roomIDEnumerator=null;
private volatile Enumeration<Area> areaEnumerator=areasPlusShips();
@Override
public boolean hasMoreElements()
{
boolean hasMore = (roomIDEnumerator != null) && roomIDEnumerator.hasMoreElements();
while(!hasMore)
{
if((areaEnumerator == null)||(!areaEnumerator.hasMoreElements()))
{
roomIDEnumerator=null;
areaEnumerator = null;
return false;
}
final Area A=areaEnumerator.nextElement();
roomIDEnumerator=A.getProperRoomnumbers().getRoomIDs();
hasMore = (roomIDEnumerator != null) && roomIDEnumerator.hasMoreElements();
}
return hasMore;
}
@Override
public String nextElement()
{
return hasMoreElements() ? (String) roomIDEnumerator.nextElement() : null;
}
};
}
@Override
public Area getFirstArea()
{
if (areas().hasMoreElements())
return areas().nextElement();
return null;
}
@Override
public Area getDefaultParentArea()
{
final String defaultParentAreaName=CMProps.getVar(CMProps.Str.DEFAULTPARENTAREA);
if((defaultParentAreaName!=null)&&(defaultParentAreaName.trim().length()>0))
return getArea(defaultParentAreaName.trim());
return null;
}
@Override
public Area getRandomArea()
{
Area A=null;
while((numAreas()>0)&&(A==null))
{
try
{
A=areasList.get(CMLib.dice().roll(1,numAreas(),-1));
}
catch(final ArrayIndexOutOfBoundsException e)
{
}
}
return A;
}
@Override
public void addGlobalHandler(final MsgListener E, final int category)
{
if(E==null)
return;
List<WeakReference<MsgListener>> V=globalHandlers.get(Integer.valueOf(category));
if(V==null)
{
V=new SLinkedList<WeakReference<MsgListener>>();
globalHandlers.put(Integer.valueOf(category),V);
}
synchronized(V)
{
for (final WeakReference<MsgListener> W : V)
{
if(W.get()==E)
return;
}
V.add(new WeakReference<MsgListener>(E));
}
}
@Override
public void delGlobalHandler(final MsgListener E, final int category)
{
final List<WeakReference<MsgListener>> V=globalHandlers.get(Integer.valueOf(category));
if((E==null)||(V==null))
return;
synchronized(V)
{
for (final WeakReference<MsgListener> W : V)
{
if(W.get()==E)
V.remove(W);
}
}
}
@Override
public MOB deity()
{
if(deities().hasMoreElements())
return deities().nextElement();
if((deityStandIn==null)
||(deityStandIn.amDestroyed())
||(deityStandIn.amDead())
||(deityStandIn.location()==null)
||(deityStandIn.location().isInhabitant(deityStandIn)))
{
if(deityStandIn!=null)
deityStandIn.destroy();
final MOB everywhereMOB=CMClass.getMOB("StdMOB");
everywhereMOB.setName(L("god"));
everywhereMOB.setLocation(this.getRandomRoom());
deityStandIn=everywhereMOB;
}
return deityStandIn;
}
@Override
public MOB getFactoryMOBInAnyRoom()
{
return getFactoryMOB(this.getRandomRoom());
}
@Override
public MOB getFactoryMOB(final Room R)
{
final MOB everywhereMOB=CMClass.getFactoryMOB();
everywhereMOB.setName(L("somebody"));
everywhereMOB.setLocation(R);
return everywhereMOB;
}
@Override
public String createNewExit(Room from, Room room, final int direction)
{
if(direction >= from.rawDoors().length)
return "Bad direction";
if(direction >= room.rawDoors().length)
return "Bad direction";
Room opRoom=from.rawDoors()[direction];
if((opRoom!=null)&&(opRoom.roomID().length()==0))
opRoom=null;
Room reverseRoom=null;
if(opRoom!=null)
reverseRoom=opRoom.rawDoors()[Directions.getOpDirectionCode(direction)];
if((reverseRoom!=null)&&(reverseRoom==from))
return "Opposite room already exists and heads this way. One-way link created.";
Exit thisExit=null;
synchronized(CMClass.getSync("SYNC"+from.roomID()))
{
from=getRoom(from);
if(opRoom!=null)
from.rawDoors()[direction]=null;
from.rawDoors()[direction]=room;
thisExit=from.getRawExit(direction);
if(thisExit==null)
{
thisExit=CMClass.getExit("StdOpenDoorway");
from.setRawExit(direction,thisExit);
}
CMLib.database().DBUpdateExits(from);
}
synchronized(CMClass.getSync("SYNC"+room.roomID()))
{
room=getRoom(room);
if(room.rawDoors()[Directions.getOpDirectionCode(direction)]==null)
{
room.rawDoors()[Directions.getOpDirectionCode(direction)]=from;
room.setRawExit(Directions.getOpDirectionCode(direction),thisExit);
CMLib.database().DBUpdateExits(room);
}
}
return "";
}
@Override
public int numRooms()
{
int total=0;
for(final Enumeration<Area> e=areas();e.hasMoreElements();)
total+=e.nextElement().properSize();
return total;
}
@Override
public boolean sendGlobalMessage(final MOB host, final int category, final CMMsg msg)
{
final List<WeakReference<MsgListener>> V=globalHandlers.get(Integer.valueOf(category));
if(V==null)
return true;
synchronized(V)
{
try
{
MsgListener O=null;
Environmental E=null;
for(final WeakReference<MsgListener> W : V)
{
O=W.get();
if(O instanceof Environmental)
{
E=(Environmental)O;
if(!CMLib.flags().isInTheGame(E,true))
{
if(!CMLib.flags().isInTheGame(E,false))
delGlobalHandler(E,category);
}
else
if(!E.okMessage(host,msg))
return false;
}
else
if(O!=null)
{
if(!O.okMessage(host, msg))
return false;
}
else
V.remove(W);
}
for(final WeakReference<MsgListener> W : V)
{
O=W.get();
if(O !=null)
O.executeMsg(host,msg);
}
}
catch(final java.lang.ArrayIndexOutOfBoundsException xx)
{
}
catch (final Exception x)
{
Log.errOut("CMMap", x);
}
}
return true;
}
@Override
public String getExtendedRoomID(final Room R)
{
if(R==null)
return "";
if(R.roomID().length()>0)
return R.roomID();
final Area A=R.getArea();
if(A==null)
return "";
final GridLocale GR=R.getGridParent();
if((GR!=null)&&(GR.roomID().length()>0))
return GR.getGridChildCode(R);
return R.roomID();
}
@Override
public String getDescriptiveExtendedRoomID(final Room room)
{
if(room==null)
return "";
final String roomID = getExtendedRoomID(room);
if(roomID.length()>0)
return roomID;
final GridLocale gridParentRoom=room.getGridParent();
if((gridParentRoom!=null)&&(gridParentRoom.roomID().length()==0))
{
for(int dir=0;dir<Directions.NUM_DIRECTIONS();dir++)
{
final Room attachedRoom = gridParentRoom.rawDoors()[dir];
if(attachedRoom != null)
{
final String attachedRoomID = getExtendedRoomID(attachedRoom);
if(attachedRoomID.length()>0)
return CMLib.directions().getFromCompassDirectionName(Directions.getOpDirectionCode(dir))+" "+attachedRoomID;
}
}
}
Area area=room.getArea();
if((area==null)&&(gridParentRoom!=null))
area=gridParentRoom.getArea();
if(area == null)
return "";
return area.Name()+"#?";
}
@Override
public String getApproximateExtendedRoomID(final Room room)
{
if(room==null)
return "";
Room validRoom = CMLib.tracking().getNearestValidIDRoom(room);
if(validRoom != null)
{
if((validRoom instanceof GridLocale)
&&(validRoom.roomID()!=null)
&&(validRoom.roomID().length()>0))
validRoom=((GridLocale)validRoom).getRandomGridChild();
return getExtendedRoomID(validRoom);
}
if(room.getArea()!=null)
return room.getArea().Name()+"#?";
return "";
}
@Override
public String getExtendedTwinRoomIDs(final Room R1,final Room R2)
{
final String R1s=getExtendedRoomID(R1);
final String R2s=getExtendedRoomID(R2);
if(R1s.compareTo(R2s)>0)
return R1s+"_"+R2s;
else
return R2s+"_"+R1s;
}
@Override
public Room getRoom(final Enumeration<Room> roomSet, final String calledThis)
{
try
{
if(calledThis==null)
return null;
if(calledThis.length()==0)
return null;
if(calledThis.endsWith(")"))
{
final int child=calledThis.lastIndexOf("#(");
if(child>1)
{
Room R=getRoom(roomSet,calledThis.substring(0,child));
if((R!=null)&&(R instanceof GridLocale))
{
R=((GridLocale)R).getGridChild(calledThis);
if(R!=null)
return R;
}
}
}
Room R=null;
if(roomSet==null)
{
final int x=calledThis.indexOf('#');
if(x>=0)
{
final Area A=getArea(calledThis.substring(0,x));
if(A!=null)
R=A.getRoom(calledThis);
if(R!=null)
return R;
}
for(final Enumeration<Area> e=this.areas();e.hasMoreElements();)
{
R = e.nextElement().getRoom(calledThis);
if(R!=null)
return R;
}
for(final Enumeration<Area> e=shipAreaEnumerator(null);e.hasMoreElements();)
{
R = e.nextElement().getRoom(calledThis);
if(R!=null)
return R;
}
}
else
{
for(final Enumeration<Room> e=roomSet;e.hasMoreElements();)
{
R=e.nextElement();
if(R.roomID().equalsIgnoreCase(calledThis))
return R;
}
}
}
catch (final java.util.NoSuchElementException x)
{
}
return null;
}
@Override
public List<Room> findRooms(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean displayOnly, final int timePct)
{
final Vector<Room> roomsV=new Vector<Room>();
if((srchStr.charAt(0)=='#')&&(mob!=null)&&(mob.location()!=null))
addWorldRoomsLiberally(roomsV,getRoom(mob.location().getArea().Name()+srchStr));
else
addWorldRoomsLiberally(roomsV,getRoom(srchStr));
addWorldRoomsLiberally(roomsV,findRooms(rooms,mob,srchStr,displayOnly,false,timePct));
return roomsV;
}
@Override
public Room findFirstRoom(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean displayOnly, final int timePct)
{
final Vector<Room> roomsV=new Vector<Room>();
if((srchStr.charAt(0)=='#')&&(mob!=null)&&(mob.location()!=null))
addWorldRoomsLiberally(roomsV,getRoom(mob.location().getArea().Name()+srchStr));
else
addWorldRoomsLiberally(roomsV,getRoom(srchStr));
if(roomsV.size()>0)
return roomsV.firstElement();
addWorldRoomsLiberally(roomsV,findRooms(rooms,mob,srchStr,displayOnly,true,timePct));
if(roomsV.size()>0)
return roomsV.firstElement();
return null;
}
public List<Room> findRooms(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean displayOnly, final boolean returnFirst, final int timePct)
{
final List<Room> foundRooms=new Vector<Room>();
Vector<Room> completeRooms=null;
try
{
completeRooms=new XVector<Room>(rooms);
}
catch(final Exception nse)
{
Log.errOut("CMMap",nse);
completeRooms=new Vector<Room>();
}
final long delay=Math.round(CMath.s_pct(timePct+"%") * 1000);
Enumeration<Room> enumSet;
enumSet=completeRooms.elements();
while(enumSet.hasMoreElements())
{
findRoomsByDisplay(mob,enumSet,foundRooms,srchStr,returnFirst,delay);
if((returnFirst)&&(foundRooms.size()>0))
return foundRooms;
if(enumSet.hasMoreElements()) CMLib.s_sleep(1000 - delay);
}
if(!displayOnly)
{
enumSet=completeRooms.elements();
while(enumSet.hasMoreElements())
{
findRoomsByDesc(mob,enumSet,foundRooms,srchStr,returnFirst,delay);
if((returnFirst)&&(foundRooms.size()>0))
return foundRooms;
if(enumSet.hasMoreElements()) CMLib.s_sleep(1000 - delay);
}
}
return foundRooms;
}
protected void findRoomsByDisplay(final MOB mob, final Enumeration<Room> rooms, final List<Room> foundRooms, String srchStr, final boolean returnFirst, final long maxTime)
{
final long startTime=System.currentTimeMillis();
try
{
srchStr=srchStr.toUpperCase();
final boolean useTimer=maxTime>1;
Room room;
for(;rooms.hasMoreElements();)
{
room=rooms.nextElement();
if((CMLib.english().containsString(CMStrings.removeColors(room.displayText(mob)),srchStr))
&&((mob==null)||CMLib.flags().canAccess(mob,room)))
foundRooms.add(room);
if((useTimer)&&((System.currentTimeMillis()-startTime)>maxTime))
return;
}
}
catch (final NoSuchElementException nse)
{
}
}
protected void findRoomsByDesc(final MOB mob, final Enumeration<Room> rooms, final List<Room> foundRooms, String srchStr, final boolean returnFirst, final long maxTime)
{
final long startTime=System.currentTimeMillis();
try
{
srchStr=srchStr.toUpperCase();
final boolean useTimer=maxTime>1;
for(;rooms.hasMoreElements();)
{
final Room room=rooms.nextElement();
if((CMLib.english().containsString(CMStrings.removeColors(room.description()),srchStr))
&&((mob==null)||CMLib.flags().canAccess(mob,room)))
foundRooms.add(room);
if((useTimer)&&((System.currentTimeMillis()-startTime)>maxTime))
return;
}
}
catch (final NoSuchElementException nse)
{
}
}
@Override
public List<MOB> findInhabitants(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
return findInhabitants(rooms,mob,srchStr,false,timePct);
}
@Override
public MOB findFirstInhabitant(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
final List<MOB> found=findInhabitants(rooms,mob,srchStr,true,timePct);
if(found.size()>0)
return found.get(0);
return null;
}
public List<MOB> findInhabitants(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean returnFirst, final int timePct)
{
final Vector<MOB> found=new Vector<MOB>();
long delay=Math.round(CMath.s_pct(timePct+"%") * 1000);
if(delay>1000)
delay=1000;
final boolean useTimer = delay>1;
final boolean allRoomsAllowed=(mob==null);
long startTime=System.currentTimeMillis();
Room room;
for(;rooms.hasMoreElements();)
{
room=rooms.nextElement();
if((room != null) && (allRoomsAllowed || CMLib.flags().canAccess(mob,room)))
{
found.addAll(room.fetchInhabitants(srchStr));
if((returnFirst)&&(found.size()>0))
return found;
}
if((useTimer)&&((System.currentTimeMillis()-startTime)>delay))
{
CMLib.s_sleep(1000 - delay);
startTime=System.currentTimeMillis();
}
}
return found;
}
@Override
public List<MOB> findInhabitantsFavorExact(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean returnFirst, final int timePct)
{
final Vector<MOB> found=new Vector<MOB>();
final Vector<MOB> exact=new Vector<MOB>();
long delay=Math.round(CMath.s_pct(timePct+"%") * 1000);
if(delay>1000)
delay=1000;
final boolean useTimer = delay>1;
final boolean allRoomsAllowed=(mob==null);
long startTime=System.currentTimeMillis();
Room room;
for(;rooms.hasMoreElements();)
{
room=rooms.nextElement();
if((room != null) && (allRoomsAllowed || CMLib.flags().canAccess(mob,room)))
{
final MOB M=room.fetchInhabitantExact(srchStr);
if(M!=null)
{
exact.add(M);
if((returnFirst)&&(exact.size()>0))
return exact;
}
found.addAll(room.fetchInhabitants(srchStr));
}
if((useTimer)&&((System.currentTimeMillis()-startTime)>delay))
{
CMLib.s_sleep(1000 - delay);
startTime=System.currentTimeMillis();
}
}
if(exact.size()>0)
return exact;
if((returnFirst)&&(found.size()>0))
{
exact.add(found.get(0));
return exact;
}
return found;
}
@Override
public List<Item> findInventory(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
return findInventory(rooms,mob,srchStr,false,timePct);
}
@Override
public Item findFirstInventory(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
final List<Item> found=findInventory(rooms,mob,srchStr,true,timePct);
if(found.size()>0)
return found.get(0);
return null;
}
public List<Item> findInventory(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean returnFirst, final int timePct)
{
final List<Item> found=new Vector<Item>();
long delay=Math.round(CMath.s_pct(timePct+"%") * 1000);
if(delay>1000)
delay=1000;
final boolean useTimer = delay>1;
long startTime=System.currentTimeMillis();
MOB M;
Room room;
if(rooms==null)
{
for(final Enumeration<MOB> e=CMLib.players().players();e.hasMoreElements();)
{
M=e.nextElement();
if(M!=null)
found.addAll(M.findItems(srchStr));
if((returnFirst)&&(found.size()>0))
return found;
}
}
else
for(;rooms.hasMoreElements();)
{
room=rooms.nextElement();
if((room != null) && ((mob==null)||CMLib.flags().canAccess(mob,room)))
{
for(int m=0;m<room.numInhabitants();m++)
{
M=room.fetchInhabitant(m);
if(M!=null)
found.addAll(M.findItems(srchStr));
}
if((returnFirst)&&(found.size()>0))
return found;
}
if((useTimer)&&((System.currentTimeMillis()-startTime)>delay))
{
CMLib.s_sleep(1000 - delay);
startTime=System.currentTimeMillis();
}
}
return found;
}
@Override
public List<Environmental> findShopStock(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
return findShopStock(rooms,mob,srchStr,false,false,timePct);
}
@Override
public Environmental findFirstShopStock(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
final List<Environmental> found=findShopStock(rooms,mob,srchStr,true,false,timePct);
if(found.size()>0)
return found.get(0);
return null;
}
@Override
public List<Environmental> findShopStockers(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
return findShopStock(rooms,mob,srchStr,false,true,timePct);
}
@Override
public Environmental findFirstShopStocker(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
final List<Environmental> found=findShopStock(rooms,mob,srchStr,true,true,timePct);
if(found.size()>0)
return found.get(0);
return null;
}
public List<Environmental> findShopStock(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean returnFirst, final boolean returnStockers, final int timePct)
{
final XVector<Environmental> found=new XVector<Environmental>();
long delay=Math.round(CMath.s_pct(timePct+"%") * 1000);
if(delay>1000)
delay=1000;
final boolean useTimer = delay>1;
long startTime=System.currentTimeMillis();
MOB M=null;
Item I=null;
final HashSet<ShopKeeper> stocks=new HashSet<ShopKeeper>(1);
final HashSet<Area> areas=new HashSet<Area>();
ShopKeeper SK=null;
final boolean allRoomsAllowed=(mob==null);
if(rooms==null)
{
for(final Enumeration<MOB> e=CMLib.players().players();e.hasMoreElements();)
{
M=e.nextElement();
if(M!=null)
{
SK=CMLib.coffeeShops().getShopKeeper(M);
if((SK!=null)&&(!stocks.contains(SK)))
{
stocks.add(SK);
final Iterator<Environmental> ei=SK.getShop().getStoreInventory(srchStr);
if(ei.hasNext())
{
if(returnFirst)
return (returnStockers)?new XVector<Environmental>(M):new XVector<Environmental>(ei);
if(returnStockers)
found.add(M);
else
found.addAll(ei);
}
}
for(int i=0;i<M.numItems();i++)
{
I=M.getItem(i);
if(I!=null)
{
SK=CMLib.coffeeShops().getShopKeeper(I);
if((SK!=null)&&(!stocks.contains(SK)))
{
stocks.add(SK);
final Iterator<Environmental> ei=SK.getShop().getStoreInventory(srchStr);
if(ei.hasNext())
{
if(returnFirst)
return (returnStockers)?new XVector<Environmental>(I):new XVector<Environmental>(ei);
if(returnStockers)
found.add(I);
else
found.addAll(ei);
}
}
}
}
}
if((useTimer)&&((System.currentTimeMillis()-startTime)>delay))
{
try
{
Thread.sleep(1000 - delay);
startTime = System.currentTimeMillis();
}
catch (final Exception ex)
{
}
}
}
}
else
for(;rooms.hasMoreElements();)
{
final Room room=rooms.nextElement();
if((room != null) && (allRoomsAllowed||CMLib.flags().canAccess(mob,room)))
{
if(!areas.contains(room.getArea()))
areas.add(room.getArea());
SK=CMLib.coffeeShops().getShopKeeper(room);
if((SK!=null)&&(!stocks.contains(SK)))
{
stocks.add(SK);
final Iterator<Environmental> ei=SK.getShop().getStoreInventory(srchStr);
if(ei.hasNext())
{
if(returnFirst)
return (returnStockers)?new XVector<Environmental>(room):new XVector<Environmental>(ei);
if(returnStockers)
found.add(room);
else
found.addAll(ei);
}
}
for(int m=0;m<room.numInhabitants();m++)
{
M=room.fetchInhabitant(m);
if(M!=null)
{
SK=CMLib.coffeeShops().getShopKeeper(M);
if((SK!=null)&&(!stocks.contains(SK)))
{
stocks.add(SK);
final Iterator<Environmental> ei=SK.getShop().getStoreInventory(srchStr);
if(ei.hasNext())
{
if(returnFirst)
return (returnStockers)?new XVector<Environmental>(M):new XVector<Environmental>(ei);
if(returnStockers)
found.add(M);
else
found.addAll(ei);
}
}
}
}
for(int i=0;i<room.numItems();i++)
{
I=room.getItem(i);
if(I!=null)
{
SK=CMLib.coffeeShops().getShopKeeper(I);
if((SK!=null)&&(!stocks.contains(SK)))
{
stocks.add(SK);
final Iterator<Environmental> ei=SK.getShop().getStoreInventory(srchStr);
if(ei.hasNext())
{
if(returnFirst)
return (returnStockers)?new XVector<Environmental>(I):new XVector<Environmental>(ei);
if(returnStockers)
found.add(I);
else
found.addAll(ei);
}
}
}
}
}
if((useTimer)&&((System.currentTimeMillis()-startTime)>delay))
{
CMLib.s_sleep(1000 - delay);
startTime=System.currentTimeMillis();
}
}
for (final Area A : areas)
{
SK=CMLib.coffeeShops().getShopKeeper(A);
if((SK!=null)&&(!stocks.contains(SK)))
{
stocks.add(SK);
final Iterator<Environmental> ei=SK.getShop().getStoreInventory(srchStr);
if(ei.hasNext())
{
if(returnFirst)
return (returnStockers)?new XVector<Environmental>(A):new XVector<Environmental>(ei);
if(returnStockers)
found.add(A);
else
found.addAll(ei);
}
}
}
return found;
}
@Override
public List<Item> findRoomItems(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean anyItems, final int timePct)
{
return findRoomItems(rooms,mob,srchStr,anyItems,false,timePct);
}
@Override
public Item findFirstRoomItem(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean anyItems, final int timePct)
{
final List<Item> found=findRoomItems(rooms,mob,srchStr,anyItems,true,timePct);
if(found.size()>0)
return found.get(0);
return null;
}
protected List<Item> findRoomItems(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean anyItems, final boolean returnFirst, final int timePct)
{
final Vector<Item> found=new Vector<Item>(); // ultimate return value
long delay=Math.round(CMath.s_pct(timePct+"%") * 1000);
if(delay>1000)
delay=1000;
final boolean useTimer = delay>1;
long startTime=System.currentTimeMillis();
final boolean allRoomsAllowed=(mob==null);
Room room;
for(;rooms.hasMoreElements();)
{
room=rooms.nextElement();
if((room != null) && (allRoomsAllowed||CMLib.flags().canAccess(mob,room)))
{
found.addAll(anyItems?room.findItems(srchStr):room.findItems(null,srchStr));
if((returnFirst)&&(found.size()>0))
return found;
}
if((useTimer)&&((System.currentTimeMillis()-startTime)>delay))
{
CMLib.s_sleep(1000 - delay);
startTime=System.currentTimeMillis();
}
}
return found;
}
@Override
public Room getRoom(final Room room)
{
if(room==null)
return null;
if(room.amDestroyed())
return getRoom(getExtendedRoomID(room));
return room;
}
@Override
public Room getRoom(final String calledThis)
{
return getRoom(null,calledThis);
}
@Override
public Room getRoomAllHosts(final String calledThis)
{
final Room R = getRoom(null,calledThis);
if(R!=null)
return R;
for(final Enumeration<CMLibrary> pl=CMLib.libraries(CMLib.Library.MAP); pl.hasMoreElements(); )
{
final WorldMap mLib = (WorldMap)pl.nextElement();
if(mLib != this)
{
final Room R2 = mLib.getRoom(calledThis);
if(R2 != null)
return R2;
}
}
return null;
}
@Override
public Enumeration<Room> rooms()
{
return new AreasRoomsEnumerator(areasPlusShips(), false);
}
@Override
public Enumeration<Room> roomsFilled()
{
return new AreasRoomsEnumerator(areasPlusShips(), true);
}
@Override
public Enumeration<MOB> worldMobs()
{
return new RoomMobsEnumerator(roomsFilled());
}
@Override
public Enumeration<Item> worldRoomItems()
{
return new RoomItemsEnumerator(roomsFilled(), false);
}
@Override
public Enumeration<Item> worldEveryItems()
{
return new RoomItemsEnumerator(roomsFilled(),true);
}
@Override
public Room getRandomRoom()
{
Room R=null;
int numRooms=-1;
for(int i=0;i<1000 && ((R==null)&&((numRooms=numRooms())>0));i++)
{
try
{
final int which=CMLib.dice().roll(1,numRooms,-1);
int total=0;
for(final Enumeration<Area> e=areas();e.hasMoreElements();)
{
final Area A=e.nextElement();
if(which<(total+A.properSize()))
{
R = A.getRandomProperRoom();
break;
}
total+=A.properSize();
}
}
catch (final NoSuchElementException e)
{
if(i > 998)
Log.errOut(e);
}
}
return R;
}
public int numDeities()
{
return deitiesList.size();
}
protected void addDeity(final Deity newOne)
{
if (!deitiesList.contains(newOne))
deitiesList.add(newOne);
}
protected void delDeity(final Deity oneToDel)
{
if (deitiesList.contains(oneToDel))
{
//final boolean deitiesRemain = deitiesList.size()>0;
deitiesList.remove(oneToDel);
//if(deitiesRemain && ((deitiesList.size()==0)))
// Log.debugOut("**DEITIES",new Exception());
}
}
@Override
public Deity getDeity(final String calledThis)
{
if((calledThis==null)||(calledThis.length()==0))
return null;
return deitiesList.find(calledThis);
}
@Override
public Enumeration<Deity> deities()
{
return new IteratorEnumeration<Deity>(deitiesList.iterator());
}
@Override
public int numShips()
{
return shipList.size();
}
protected void addShip(final Boardable newOne)
{
if (!shipList.contains(newOne))
{
shipList.add(newOne);
final Area area=newOne.getArea();
if((area!=null)&&(area.getAreaState()==Area.State.ACTIVE))
area.setAreaState(Area.State.ACTIVE);
}
}
protected void delShip(final Boardable oneToDel)
{
if(oneToDel!=null)
{
shipList.remove(oneToDel);
final Item shipI = oneToDel.getBoardableItem();
if(shipI instanceof Boardable)
{
final Boardable boardableShipI = (Boardable)shipI;
shipList.remove(boardableShipI);
}
final Area area=oneToDel.getArea();
if(area!=null)
{
if(area instanceof Boardable)
{
final Boardable boardableShipA = (Boardable)area;
shipList.remove(boardableShipA);
}
area.setAreaState(Area.State.STOPPED);
}
}
}
@Override
public Boardable getShip(final String calledThis)
{
for (final Boardable S : shipList)
{
if (S.Name().equalsIgnoreCase(calledThis))
return S;
}
return null;
}
@Override
public Boardable findShip(final String s, final boolean exactOnly)
{
return (Boardable)CMLib.english().fetchEnvironmental(shipList, s, exactOnly);
}
@Override
public Enumeration<Boardable> ships()
{
return new IteratorEnumeration<Boardable>(shipList.iterator());
}
public Enumeration<Room> shipsRoomEnumerator(final Area inA)
{
return new Enumeration<Room>()
{
private Enumeration<Room> cur = null;
private Enumeration<Area> cA = shipAreaEnumerator(inA);
@Override
public boolean hasMoreElements()
{
boolean hasMore = (cur != null) && cur.hasMoreElements();
while(!hasMore)
{
if((cA == null)||(!cA.hasMoreElements()))
{
cur=null;
cA = null;
return false;
}
cur = cA.nextElement().getProperMap();
hasMore = (cur != null) && cur.hasMoreElements();
}
return hasMore;
}
@Override
public Room nextElement()
{
if(!hasMoreElements())
throw new NoSuchElementException();
return cur.nextElement();
}
};
}
public Enumeration<Area> shipAreaEnumerator(final Area inA)
{
return new Enumeration<Area>()
{
private volatile Area nextArea=null;
private volatile Enumeration<Boardable> shipsEnum=ships();
@Override
public boolean hasMoreElements()
{
while(nextArea == null)
{
if((shipsEnum==null)||(!shipsEnum.hasMoreElements()))
{
shipsEnum=null;
return false;
}
final Boardable ship=shipsEnum.nextElement();
if((ship!=null)&&(ship.getArea()!=null))
{
if((inA==null)||(areaLocation(ship)==inA))
nextArea=ship.getArea();
}
}
return (nextArea != null);
}
@Override
public Area nextElement()
{
if(!hasMoreElements())
throw new NoSuchElementException();
final Area A=nextArea;
this.nextArea=null;
return A;
}
};
}
@Override
public void renameRooms(final Area A, final String oldName, final List<Room> allMyDamnRooms)
{
final List<Room> onesToRenumber=new Vector<Room>();
for(Room R : allMyDamnRooms)
{
synchronized(CMClass.getSync("SYNC"+R.roomID()))
{
R=getRoom(R);
R.setArea(A);
if(oldName!=null)
{
if(R.roomID().toUpperCase().startsWith(oldName.toUpperCase()+"#"))
{
Room R2=A.getRoom(A.Name()+"#"+R.roomID().substring(oldName.length()+1));
if(R2 == null)
R2=getRoom(A.Name()+"#"+R.roomID().substring(oldName.length()+1));
if((R2==null)||(!R2.roomID().startsWith(A.Name()+"#")))
{
final String oldID=R.roomID();
R.setRoomID(A.Name()+"#"+R.roomID().substring(oldName.length()+1));
CMLib.database().DBReCreate(R,oldID);
}
else
onesToRenumber.add(R);
}
else
CMLib.database().DBUpdateRoom(R);
}
}
}
if(oldName!=null)
{
for(final Room R: onesToRenumber)
{
final String oldID=R.roomID();
R.setRoomID(A.getNewRoomID(R,-1));
CMLib.database().DBReCreate(R,oldID);
}
}
}
@Override
public int getRoomDir(final Room from, final Room to)
{
if((from==null)||(to==null))
return -1;
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
if(from.getRoomInDir(d)==to)
return d;
}
return -1;
}
@Override
public Area getTargetArea(final Room from, final Exit to)
{
final Room R=getTargetRoom(from, to);
if(R==null)
return null;
return R.getArea();
}
@Override
public Room getTargetRoom(final Room from, final Exit to)
{
if((from==null)||(to==null))
return null;
final int d=getExitDir(from, to);
if(d<0)
return null;
return from.getRoomInDir(d);
}
@Override
public int getExitDir(final Room from, final Exit to)
{
if((from==null)||(to==null))
return -1;
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
if(from.getExitInDir(d)==to)
return d;
if(from.getRawExit(d)==to)
return d;
if(from.getReverseExit(d)==to)
return d;
}
return -1;
}
@Override
public Room findConnectingRoom(final Room room)
{
if(room==null)
return null;
Room R=null;
final Vector<Room> otherChoices=new Vector<Room>();
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
R=room.getRoomInDir(d);
if(R!=null)
{
for(int d1=Directions.NUM_DIRECTIONS()-1;d1>=0;d1--)
{
if(R.getRoomInDir(d1)==room)
{
if(R.getArea()==room.getArea())
return R;
otherChoices.addElement(R);
}
}
}
}
for(final Enumeration<Room> e=rooms();e.hasMoreElements();)
{
R=e.nextElement();
if(R==room)
continue;
for(int d1=Directions.NUM_DIRECTIONS()-1;d1>=0;d1--)
{
if(R.getRoomInDir(d1)==room)
{
if(R.getArea()==room.getArea())
return R;
otherChoices.addElement(R);
}
}
}
if(otherChoices.size()>0)
return otherChoices.firstElement();
return null;
}
@Override
public boolean isClearableRoom(final Room R)
{
if((R==null)||(R.amDestroyed()))
return true;
MOB M=null;
Room sR=null;
for(int i=0;i<R.numInhabitants();i++)
{
M=R.fetchInhabitant(i);
if(M==null)
continue;
sR=M.getStartRoom();
if((sR!=null)
&&(sR != R)
&&(!sR.roomID().equals(R.roomID()))
&&(!sR.amDestroyed()))
{
CMLib.tracking().wanderAway(M, false, true);
if(M.location()==R)
return false;
}
if(M.session()!=null)
return false;
}
Item I=null;
for(int i=0;i<R.numItems();i++)
{
I=R.getItem(i);
if((I!=null)
&&((I.expirationDate()!=0)
||((I instanceof DeadBody)&&(((DeadBody)I).isPlayerCorpse()))
||((I instanceof PrivateProperty)&&(((PrivateProperty)I).getOwnerName().length()>0))))
return false;
}
for(final Enumeration<Ability> a=R.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)&&(!A.isSavable()))
return false;
}
return true;
}
@Override
public boolean explored(final Room R)
{
if((R==null)
||(CMath.bset(R.phyStats().sensesMask(),PhyStats.SENSE_ROOMUNEXPLORABLE))
||(R.getArea()==null))
return false;
return false;
}
public class AreasRoomsEnumerator implements Enumeration<Room>
{
private final Enumeration<Area> curAreaEnumeration;
private final boolean addSkys;
private volatile Enumeration<Room> curRoomEnumeration = null;
public AreasRoomsEnumerator(final Enumeration<Area> curAreaEnumeration, final boolean includeSkys)
{
addSkys = includeSkys;
this.curAreaEnumeration=curAreaEnumeration;
}
@Override
public boolean hasMoreElements()
{
boolean hasMore = (curRoomEnumeration!=null)&&(curRoomEnumeration.hasMoreElements());
while(!hasMore)
{
if((curAreaEnumeration == null)||(!curAreaEnumeration.hasMoreElements()))
{
curRoomEnumeration = null;
return false;
}
if(addSkys)
curRoomEnumeration=curAreaEnumeration.nextElement().getFilledProperMap();
else
curRoomEnumeration=curAreaEnumeration.nextElement().getProperMap();
hasMore = (curRoomEnumeration!=null)&&(curRoomEnumeration.hasMoreElements());
}
return hasMore;
}
@Override
public Room nextElement()
{
if(!hasMoreElements())
throw new NoSuchElementException();
return curRoomEnumeration.nextElement();
}
}
public class RoomMobsEnumerator implements Enumeration<MOB>
{
private final Enumeration<Room> curRoomEnumeration;
private volatile Enumeration<MOB> curMobEnumeration = null;
public RoomMobsEnumerator(final Enumeration<Room> curRoomEnumeration)
{
this.curRoomEnumeration=curRoomEnumeration;
}
@Override
public boolean hasMoreElements()
{
boolean hasMore = (curMobEnumeration!=null)&&(curMobEnumeration.hasMoreElements());
while(!hasMore)
{
if((curRoomEnumeration == null)||(!curRoomEnumeration.hasMoreElements()))
{
curMobEnumeration = null;
return false;
}
curMobEnumeration=curRoomEnumeration.nextElement().inhabitants();
hasMore = (curMobEnumeration!=null)&&(curMobEnumeration.hasMoreElements());
}
return hasMore;
}
@Override
public MOB nextElement()
{
if(!hasMoreElements())
throw new NoSuchElementException();
return curMobEnumeration.nextElement();
}
}
public class RoomItemsEnumerator implements Enumeration<Item>
{
private final Enumeration<Room> curRoomEnumeration;
private final boolean includeMobItems;
private volatile Enumeration<Item> curItemEnumeration = null;
public RoomItemsEnumerator(final Enumeration<Room> curRoomEnumeration, final boolean includeMobItems)
{
this.curRoomEnumeration=curRoomEnumeration;
this.includeMobItems=includeMobItems;
}
@Override
public boolean hasMoreElements()
{
boolean hasMore = (curItemEnumeration!=null)&&(curItemEnumeration.hasMoreElements());
while(!hasMore)
{
if((curRoomEnumeration == null)||(!curRoomEnumeration.hasMoreElements()))
{
curItemEnumeration = null;
return false;
}
if(includeMobItems)
curItemEnumeration=curRoomEnumeration.nextElement().itemsRecursive();
else
curItemEnumeration=curRoomEnumeration.nextElement().items();
hasMore = (curItemEnumeration!=null)&&(curItemEnumeration.hasMoreElements());
}
return hasMore;
}
@Override
public Item nextElement()
{
if(!hasMoreElements())
throw new NoSuchElementException();
return curItemEnumeration.nextElement();
}
}
@Override
public void obliterateMapRoom(final Room deadRoom)
{
obliterateRoom(deadRoom,null,true);
}
@Override
public void destroyRoomObject(final Room deadRoom)
{
obliterateRoom(deadRoom,null,false);
}
protected void obliterateRoom(final Room deadRoom, final List<Room> linkInRooms, final boolean includeDB)
{
for(final Enumeration<Ability> a=deadRoom.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if(A!=null)
{
A.unInvoke();
deadRoom.delEffect(A);
}
}
try
{
final List<Pair<Room,Integer>> roomsToDo=new LinkedList<Pair<Room,Integer>>();
final Enumeration<Room> r;
if(linkInRooms != null)
r=new IteratorEnumeration<Room>(linkInRooms.iterator());
else
r=rooms();
for(;r.hasMoreElements();)
{
final Room R=getRoom(r.nextElement());
if(R!=null)
{
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
final Room thatRoom=R.rawDoors()[d];
if(thatRoom==deadRoom)
roomsToDo.add(new Pair<Room,Integer>(R,Integer.valueOf(d)));
}
}
}
for(final Pair<Room,Integer> p : roomsToDo)
{
final Room R=p.first;
final int d=p.second.intValue();
synchronized(CMClass.getSync("SYNC"+R.roomID()))
{
R.rawDoors()[d]=null;
if((R.getRawExit(d)!=null)&&(R.getRawExit(d).isGeneric()))
{
final Exit GE=R.getRawExit(d);
GE.setTemporaryDoorLink(deadRoom.roomID());
}
if(includeDB)
CMLib.database().DBUpdateExits(R);
}
}
}
catch (final NoSuchElementException e)
{
}
emptyRoom(deadRoom,null,true);
deadRoom.destroy();
if(deadRoom instanceof GridLocale)
((GridLocale)deadRoom).clearGrid(null);
if(includeDB)
CMLib.database().DBDeleteRoom(deadRoom);
}
@Override
public void emptyAreaAndDestroyRooms(final Area area)
{
for(final Enumeration<Ability> a=area.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if(A!=null)
{
A.unInvoke();
area.delEffect(A);
}
}
for(final Enumeration<Room> e=area.getProperMap();e.hasMoreElements();)
{
final Room R=e.nextElement();
emptyRoom(R,null,true);
R.destroy();
}
}
@Override
public Room roomLocation(final Environmental E)
{
if(E==null)
return null;
if((E instanceof Area)&&(!((Area)E).isProperlyEmpty()))
return ((Area)E).getRandomProperRoom();
else
if(E instanceof Room)
return (Room)E;
else
if(E instanceof MOB)
return ((MOB)E).location();
else
if((E instanceof Item)&&(((Item)E).owner() instanceof Room))
return (Room)((Item)E).owner();
else
if((E instanceof Item)&&(((Item)E).owner() instanceof MOB))
return ((MOB)((Item)E).owner()).location();
else
if(E instanceof Ability)
return roomLocation(((Ability)E).affecting());
else
if(E instanceof Exit)
return roomLocation(((Exit)E).lastRoomUsedFrom(null));
return null;
}
@Override
public Area getStartArea(final Environmental E)
{
if(E instanceof Area)
return (Area)E;
final Room R=getStartRoom(E);
if(R==null)
return null;
return R.getArea();
}
@Override
public Room getStartRoom(final Environmental E)
{
if(E ==null)
return null;
if(E instanceof MOB)
return ((MOB)E).getStartRoom();
if(E instanceof Item)
{
if(((Item)E).owner() instanceof MOB)
return getStartRoom(((Item)E).owner());
if(CMLib.flags().isGettable((Item)E))
return null;
}
if(E instanceof Ability)
return getStartRoom(((Ability)E).affecting());
if((E instanceof Area)&&(!((Area)E).isProperlyEmpty()))
return ((Area)E).getRandomProperRoom();
if(E instanceof Room)
return (Room)E;
return roomLocation(E);
}
@Override
public ThreadGroup getOwnedThreadGroup(final CMObject E)
{
final Area area=areaLocation(E);
if(area != null)
{
final int theme=area.getTheme();
if((theme>0)&&(theme<Area.THEME_NAMES.length))
return CMProps.getPrivateOwner(Area.THEME_NAMES[theme]+"AREAS");
}
return null;
}
@Override
public Area areaLocation(final CMObject E)
{
if(E==null)
return null;
if(E instanceof Area)
return (Area)E;
else
if(E instanceof Room)
return ((Room)E).getArea();
else
if(E instanceof MOB)
return areaLocation(((MOB)E).location());
else
if(E instanceof Item)
return areaLocation(((Item) E).owner());
else
if((E instanceof Ability)&&(((Ability)E).affecting()!=null))
return areaLocation(((Ability)E).affecting());
else
if(E instanceof Exit)
return areaLocation(((Exit)E).lastRoomUsedFrom(null));
return null;
}
@Override
public Room getSafeRoomToMovePropertyTo(final Room room, final PrivateProperty I)
{
if(I instanceof Boardable)
{
final Room R=getRoom(((Boardable)I).getHomePortID());
if((R!=null)&&(R!=room)&&(!R.amDestroyed()))
return R;
}
if(room != null)
{
Room R=null;
if(room.getGridParent()!=null)
{
R=getRoom(room.getGridParent());
if((R!=null)&&(R!=room)&&(!R.amDestroyed())&&(R.roomID().length()>0))
return R;
}
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
R=getRoom(room.getRoomInDir(d));
if((R!=null)&&(R!=room)&&(!R.amDestroyed())&&(R.roomID().length()>0))
return R;
}
if(room.getGridParent()!=null)
{
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
R=getRoom(room.getGridParent().getRoomInDir(d));
if((R!=null)&&(R!=room)&&(!R.amDestroyed())&&(R.roomID().length()>0))
return R;
}
}
final Area A=room.getArea();
if(A!=null)
{
for(int i=0;i<A.numberOfProperIDedRooms();i++)
{
R=getRoom(A.getRandomProperRoom());
if((R!=null)&&(R!=room)&&(!R.amDestroyed())&&(R.roomID().length()>0))
return R;
}
}
}
for(int i=0;i<100;i++)
{
final Room R=getRoom(this.getRandomRoom());
if((R!=null)&&(R!=room)&&(!R.amDestroyed())&&(R.roomID().length()>0))
return R;
}
return null;
}
@Override
public void emptyRoom(final Room room, final Room toRoom, final boolean clearPlayers)
{
if(room==null)
return;
// this will empty grid rooms so that
// the code below can delete them or whatever.
if(room instanceof GridLocale)
{
for(final Iterator<Room> r=((GridLocale)room).getExistingRooms();r.hasNext();)
emptyRoom(r.next(), toRoom, clearPlayers);
}
// this will empty skys and underwater of mobs so that
// the code below can delete them or whatever.
room.clearSky();
if(toRoom != null)
{
for(final Enumeration<MOB> i=room.inhabitants();i.hasMoreElements();)
{
final MOB M=i.nextElement();
if(M!=null)
toRoom.bringMobHere(M,false);
}
}
else
if(clearPlayers)
{
for(final Enumeration<MOB> i=room.inhabitants();i.hasMoreElements();)
{
final MOB M=i.nextElement();
if((M!=null) && (M.isPlayer()))
{
Room sR=M.getStartRoom();
int attempts=1000;
while(((sR == room)||(sR==null))
&&(--attempts>0))
sR=getRandomRoom();
if((sR!=null)&&(sR!=room))
sR.bringMobHere(M,true);
else
room.delInhabitant(M);
}
}
}
for(final Enumeration<MOB> i=room.inhabitants();i.hasMoreElements();)
{
final MOB M=i.nextElement();
if((M!=null)
&&(!M.isPlayer())
&&(M.isSavable()) // this is almost certainly to protect Quest mobs, which are just about the only unsavable things.
&&((M.amFollowing()==null)||(!M.amFollowing().isPlayer())))
{
final Room startRoom = M.getStartRoom();
final Area startArea = (startRoom == null) ? null : startRoom.getArea();
if((startRoom==null)
||(startRoom==room)
||(startRoom.amDestroyed())
||(startArea==null)
||(startArea.amDestroyed())
||(startRoom.ID().length()==0))
M.destroy();
else
M.getStartRoom().bringMobHere(M,false);
}
}
Item I=null;
if(toRoom != null)
{
for(final Enumeration<Item> i=room.items();i.hasMoreElements();)
{
I=i.nextElement();
if(I!=null)
toRoom.moveItemTo(I,ItemPossessor.Expire.Player_Drop);
}
}
else
{
for(final Enumeration<Item> i=room.items();i.hasMoreElements();)
{
I=i.nextElement();
if(I != null)
{
if((I instanceof PrivateProperty)
&&((((PrivateProperty)I).getOwnerName().length()>0)))
{
final Room R=getSafeRoomToMovePropertyTo(room, (PrivateProperty)I);
if((R!=null)
&&(R!=room))
R.moveItemTo(I,ItemPossessor.Expire.Player_Drop);
}
else
I.destroy();
}
}
}
room.clearSky();
// clear debri only clears things by their start rooms, not location, so only roomid matters.
if(room.roomID().length()>0)
CMLib.threads().clearDebri(room,0);
if(room instanceof GridLocale)
{
for(final Iterator<Room> r=((GridLocale)room).getExistingRooms();r.hasNext();)
emptyRoom(r.next(), toRoom, clearPlayers);
}
}
@Override
public void obliterateMapArea(final Area A)
{
obliterateArea(A,true);
for(final Enumeration<Area> a=areas();a.hasMoreElements();)
{
final Area A2=a.nextElement();
if((A2!=null)
&&(A2.isSavable())
&&(A2.isParent(A)||A2.isChild(A)))
{
A2.removeParent(A);
A2.removeChild(A);
CMLib.database().DBUpdateArea(A2.Name(), A2);
}
}
}
@Override
public void destroyAreaObject(final Area A)
{
obliterateArea(A,false);
}
protected void obliterateArea(final Area A, final boolean includeDB)
{
if(A==null)
return;
A.setAreaState(Area.State.STOPPED);
if(A instanceof SpaceShip)
CMLib.tech().unregisterAllElectronics(CMLib.tech().getElectronicsKey(A));
final List<Room> allRooms=new LinkedList<Room>();
for(int i=0;i<2;i++)
{
for(final Enumeration<Room> e=A.getProperMap();e.hasMoreElements();)
{
final Room R=e.nextElement();
if(R!=null)
{
allRooms.add(R);
emptyRoom(R,null,false);
R.clearSky();
}
}
}
if(includeDB)
CMLib.database().DBDeleteAreaAndRooms(A);
final List<Room> linkInRooms = new LinkedList<Room>();
for(final Enumeration<Room> r=rooms();r.hasMoreElements();)
{
final Room R=getRoom(r.nextElement());
if(R!=null)
{
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
final Room thatRoom=R.rawDoors()[d];
if((thatRoom!=null)
&&(thatRoom.getArea()==A))
{
linkInRooms.add(R);
break;
}
}
}
}
for(final Room R : allRooms)
obliterateRoom(R,linkInRooms,includeDB);
delArea(A);
A.destroy(); // why not?
}
public CMMsg resetMsg=null;
@Override
public void resetRoom(final Room room)
{
resetRoom(room,false);
}
@Override
public void resetRoom(Room room, final boolean rebuildGrids)
{
if(room==null)
return;
if(room.roomID().length()==0)
return;
synchronized(CMClass.getSync("SYNC"+room.roomID()))
{
room=getRoom(room);
if((rebuildGrids)&&(room instanceof GridLocale))
((GridLocale)room).clearGrid(null);
final boolean mobile=room.getMobility();
try
{
room.toggleMobility(false);
if(resetMsg==null)
resetMsg=CMClass.getMsg(CMClass.sampleMOB(),room,CMMsg.MSG_ROOMRESET,null);
resetMsg.setTarget(room);
room.executeMsg(room,resetMsg);
if(room.isSavable())
emptyRoom(room,null,false);
for(final Enumeration<Ability> a=room.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)&&(A.canBeUninvoked()))
A.unInvoke();
}
if(room.isSavable())
{
CMLib.database().DBReReadRoomData(room);
CMLib.database().DBReadContent(room.roomID(),room,true);
}
room.startItemRejuv();
room.setResource(-1);
}
finally
{
room.toggleMobility(mobile);
}
}
}
@Override
public Room findWorldRoomLiberally(final MOB mob, final String cmd, final String srchWhatAERIPMVK, final int timePct, final long maxMillis)
{
final List<Room> rooms=findWorldRoomsLiberally(mob,cmd,srchWhatAERIPMVK,null,true,timePct, maxMillis);
if((rooms!=null)&&(rooms.size()!=0))
return rooms.get(0);
return null;
}
@Override
public List<Room> findWorldRoomsLiberally(final MOB mob, final String cmd, final String srchWhatAERIPMVK, final int timePct, final long maxMillis)
{
return findWorldRoomsLiberally(mob,cmd,srchWhatAERIPMVK,null,false,timePct,maxMillis);
}
@Override
public Room findAreaRoomLiberally(final MOB mob, final Area A,final String cmd, final String srchWhatAERIPMVK, final int timePct)
{
final List<Room> rooms=findWorldRoomsLiberally(mob,cmd,srchWhatAERIPMVK,A,true,timePct,120);
if((rooms!=null)&&(rooms.size()!=0))
return rooms.get(0);
return null;
}
@Override
public List<Room> findAreaRoomsLiberally(final MOB mob, final Area A,final String cmd, final String srchWhatAERIPMVK, final int timePct)
{
return findWorldRoomsLiberally(mob,cmd,srchWhatAERIPMVK,A,false,timePct,120);
}
protected Room addWorldRoomsLiberally(final List<Room> rooms, final List<? extends Environmental> choicesV)
{
if(choicesV==null)
return null;
if(rooms!=null)
{
for(final Environmental E : choicesV)
addWorldRoomsLiberally(rooms,roomLocation(E));
return null;
}
else
{
Room room=null;
int tries=0;
while(((room==null)||(room.roomID().length()==0))&&((++tries)<200))
room=roomLocation(choicesV.get(CMLib.dice().roll(1,choicesV.size(),-1)));
return room;
}
}
protected Room addWorldRoomsLiberally(final List<Room> rooms, final Room room)
{
if(room==null)
return null;
if(rooms!=null)
{
if(!rooms.contains(room))
rooms.add(room);
return null;
}
return room;
}
protected Room addWorldRoomsLiberally(final List<Room>rooms, final Area area)
{
if((area==null)||(area.isProperlyEmpty()))
return null;
return addWorldRoomsLiberally(rooms,area.getRandomProperRoom());
}
protected List<Room> returnResponse(final List<Room> rooms, final Room room)
{
if(rooms!=null)
return rooms;
if(room==null)
return new Vector<Room>(1);
return new XVector<Room>(room);
}
protected boolean enforceTimeLimit(final long startTime, final long maxMillis)
{
if(maxMillis<=0)
return false;
return ((System.currentTimeMillis() - startTime)) > maxMillis;
}
protected List<MOB> checkMOBCachedList(final List<MOB> list)
{
if (list != null)
{
for(final Environmental E : list)
if(E.amDestroyed())
return null;
}
return list;
}
protected List<Item> checkInvCachedList(final List<Item> list)
{
if (list != null)
{
for(final Item E : list)
if((E.amDestroyed())||(!(E.owner() instanceof MOB)))
return null;
}
return list;
}
protected List<Item> checkRoomItemCachedList(final List<Item> list)
{
if (list != null)
{
for(final Item E : list)
if((E.amDestroyed())||(!(E.owner() instanceof Room)))
return null;
}
return list;
}
@SuppressWarnings("unchecked")
public Map<String,List<MOB>> getMOBFinder()
{
Map<String,List<MOB>> finder=(Map<String,List<MOB>>)Resources.getResource("SYSTEM_MOB_FINDER_CACHE");
if(finder==null)
{
finder=new PrioritizingLimitedMap<String,List<MOB>>(10,EXPIRE_5MINS,EXPIRE_10MINS,100);
Resources.submitResource("SYSTEM_MOB_FINDER_CACHE",finder);
}
return finder;
}
@SuppressWarnings("unchecked")
public Map<String,Area> getAreaFinder()
{
Map<String,Area> finder=(Map<String,Area>)Resources.getResource("SYSTEM_AREA_FINDER_CACHE");
if(finder==null)
{
finder=new PrioritizingLimitedMap<String,Area>(50,EXPIRE_30MINS,EXPIRE_1HOUR,100);
Resources.submitResource("SYSTEM_AREA_FINDER_CACHE",finder);
}
return finder;
}
@SuppressWarnings("unchecked")
public Map<String,List<Item>> getRoomItemFinder()
{
Map<String,List<Item>> finder=(Map<String,List<Item>>)Resources.getResource("SYSTEM_RITEM_FINDER_CACHE");
if(finder==null)
{
finder=new PrioritizingLimitedMap<String,List<Item>>(10,EXPIRE_5MINS,EXPIRE_10MINS,100);
Resources.submitResource("SYSTEM_RITEM_FINDER_CACHE",finder);
}
return finder;
}
@SuppressWarnings("unchecked")
public Map<String,List<Item>> getInvItemFinder()
{
Map<String,List<Item>> finder=(Map<String,List<Item>>)Resources.getResource("SYSTEM_IITEM_FINDER_CACHE");
if(finder==null)
{
finder=new PrioritizingLimitedMap<String,List<Item>>(10,EXPIRE_1MIN,EXPIRE_10MINS,100);
Resources.submitResource("SYSTEM_IITEM_FINDER_CACHE",finder);
}
return finder;
}
@SuppressWarnings("unchecked")
public Map<String,List<Environmental>> getStockFinder()
{
Map<String,List<Environmental>> finder=(Map<String,List<Environmental>>)Resources.getResource("SYSTEM_STOCK_FINDER_CACHE");
if(finder==null)
{
finder=new PrioritizingLimitedMap<String,List<Environmental>>(10,EXPIRE_10MINS,EXPIRE_1HOUR,100);
Resources.submitResource("SYSTEM_STOCK_FINDER_CACHE",finder);
}
return finder;
}
@SuppressWarnings("unchecked")
public Map<String,List<Room>> getRoomFinder()
{
Map<String,List<Room>> finder=(Map<String,List<Room>>)Resources.getResource("SYSTEM_ROOM_FINDER_CACHE");
if(finder==null)
{
finder=new PrioritizingLimitedMap<String,List<Room>>(20,EXPIRE_20MINS,EXPIRE_1HOUR,100);
Resources.submitResource("SYSTEM_ROOM_FINDER_CACHE",finder);
}
return finder;
}
protected List<Room> findWorldRoomsLiberally(final MOB mob,
final String cmd,
final String srchWhatAERIPMVK,
Area area,
final boolean returnFirst,
final int timePct,
final long maxMillis)
{
Room room=null;
// wish this stuff could be cached, even temporarily, however,
// far too much of the world is dynamic, and far too many searches
// are looking for dynamic things. the cached results would be useless
// as soon as they are put away -- that's why the limited caches time them out!
final boolean disableCaching= CMProps.getBoolVar(CMProps.Bool.MAPFINDSNOCACHE);
final Vector<Room> rooms=(returnFirst)?null:new Vector<Room>();
final Room curRoom=(mob!=null)?mob.location():null;
boolean searchWeakAreas=false;
boolean searchStrictAreas=false;
boolean searchRooms=false;
boolean searchPlayers=false;
boolean searchItems=false;
boolean searchInhabs=false;
boolean searchInventories=false;
boolean searchStocks=false;
final char[] flags = srchWhatAERIPMVK.toUpperCase().toCharArray();
for (final char flag : flags)
{
switch(flag)
{
case 'E':
searchWeakAreas = true;
break;
case 'A':
searchStrictAreas = true;
break;
case 'R':
searchRooms = true;
break;
case 'P':
searchPlayers = true;
break;
case 'I':
searchItems = true;
break;
case 'M':
searchInhabs = true;
break;
case 'V':
searchInventories = true;
break;
case 'K':
searchStocks = true;
break;
}
}
final long startTime = System.currentTimeMillis();
if(searchRooms)
{
final int dirCode=CMLib.directions().getGoodDirectionCode(cmd);
if((dirCode>=0)&&(curRoom!=null))
room=addWorldRoomsLiberally(rooms,curRoom.rawDoors()[dirCode]);
if(room==null)
room=addWorldRoomsLiberally(rooms,getRoom(cmd));
if((room == null) && (curRoom != null) && (curRoom.getArea()!=null))
room=addWorldRoomsLiberally(rooms,curRoom.getArea().getRoom(cmd));
}
if(room==null)
{
// first get room ids
if((cmd.charAt(0)=='#')&&(curRoom!=null)&&(searchRooms))
{
room=addWorldRoomsLiberally(rooms,getRoom(curRoom.getArea().Name()+cmd));
if(room == null)
room=addWorldRoomsLiberally(rooms,curRoom.getArea().getRoom(curRoom.getArea().Name()+cmd));
}
else
{
final String srchStr=cmd;
if(searchPlayers)
{
// then look for players
final MOB M=CMLib.sessions().findCharacterOnline(srchStr,false);
if(M!=null)
room=addWorldRoomsLiberally(rooms,M.location());
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
// search areas strictly
if(searchStrictAreas && (room==null) && (area==null))
{
area=getArea(srchStr);
if((area!=null) &&(area.properSize()>0) &&(area.getProperRoomnumbers().roomCountAllAreas()>0))
room=addWorldRoomsLiberally(rooms,area);
area=null;
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
final Area A=area;
final MultiEnumeratorBuilder<Room> roomer = new MultiEnumeratorBuilder<Room>()
{
@Override
public MultiEnumeration<Room> getList()
{
if(A==null)
return new MultiEnumeration<Room>(roomsFilled());
else
return new MultiEnumeration<Room>()
.addEnumeration(A.getProperMap())
.addEnumeration(shipsRoomEnumerator(A));
}
};
// no good, so look for room inhabitants
if(searchInhabs && room==null)
{
final Map<String,List<MOB>> finder=getMOBFinder();
List<MOB> candidates=null;
if((mob==null)||(mob.isMonster()))
{
candidates=checkMOBCachedList(finder.get(srchStr.toLowerCase()));
if(returnFirst&&(candidates!=null)&&(candidates.size()>1))
candidates=new XVector<MOB>(candidates.get(0));
}
if(candidates==null)
{
candidates=findInhabitants(roomer.getList(), mob, srchStr,returnFirst, timePct);
if((!disableCaching)&&(!returnFirst)&&((mob==null)||(mob.isMonster())))
finder.put(srchStr.toLowerCase(), candidates);
}
if(candidates.size()>0)
room=addWorldRoomsLiberally(rooms,candidates);
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
// now check room text
if(searchRooms && room==null)
{
final Map<String,List<Room>> finder=getRoomFinder();
List<Room> candidates=null;
if((mob==null)||(mob.isMonster()))
{
candidates=finder.get(srchStr.toLowerCase());
if(returnFirst&&(candidates!=null)&&(candidates.size()>1))
candidates=new XVector<Room>(candidates.get(0));
}
if(candidates==null)
{
candidates=findRooms(roomer.getList(), mob, srchStr, false,returnFirst, timePct);
if((!disableCaching)&&(!returnFirst)&&((mob==null)||(mob.isMonster())))
finder.put(srchStr.toLowerCase(), candidates);
}
if(candidates.size()>0)
room=addWorldRoomsLiberally(rooms,candidates);
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
// check floor items
if(searchItems && room==null)
{
final Map<String,List<Item>> finder=getRoomItemFinder();
List<Item> candidates=null;
if((mob==null)||(mob.isMonster()))
{
candidates=checkRoomItemCachedList(finder.get(srchStr.toLowerCase()));
if(returnFirst&&(candidates!=null)&&(candidates.size()>1))
candidates=new XVector<Item>(candidates.get(0));
}
if(candidates==null)
{
candidates=findRoomItems(roomer.getList(), mob, srchStr, false,returnFirst,timePct);
if((!disableCaching)&&(!returnFirst)&&((mob==null)||(mob.isMonster())))
finder.put(srchStr.toLowerCase(), candidates);
}
if(candidates.size()>0)
room=addWorldRoomsLiberally(rooms,candidates);
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
// check inventories
if(searchInventories && room==null)
{
final Map<String,List<Item>> finder=getInvItemFinder();
List<Item> candidates=null;
if((mob==null)||(mob.isMonster()))
{
candidates=checkInvCachedList(finder.get(srchStr.toLowerCase()));
if(returnFirst&&(candidates!=null)&&(candidates.size()>1))
candidates=new XVector<Item>(candidates.get(0));
}
if(candidates==null)
{
candidates=findInventory(roomer.getList(), mob, srchStr, returnFirst,timePct);
if((!disableCaching)&&(!returnFirst)&&((mob==null)||(mob.isMonster())))
finder.put(srchStr.toLowerCase(), candidates);
}
if(candidates.size()>0)
room=addWorldRoomsLiberally(rooms,candidates);
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
// check stocks
if(searchStocks && room==null)
{
final Map<String,List<Environmental>> finder=getStockFinder();
List<Environmental> candidates=null;
if((mob==null)||(mob.isMonster()))
{
candidates=finder.get(srchStr.toLowerCase());
if(returnFirst&&(candidates!=null)&&(candidates.size()>1))
candidates=new XVector<Environmental>(candidates.get(0));
}
if(candidates==null)
{
candidates=findShopStock(roomer.getList(), mob, srchStr, returnFirst,false,timePct);
if((!disableCaching)&&(!returnFirst)&&((mob==null)||(mob.isMonster())))
finder.put(srchStr.toLowerCase(), candidates);
}
if(candidates.size()>0)
room=addWorldRoomsLiberally(rooms,candidates);
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
// search areas weakly
if(searchWeakAreas && (room==null) && (A==null))
{
final Area A2=findArea(srchStr);
if((A2!=null) &&(A2.properSize()>0) &&(A2.getProperRoomnumbers().roomCountAllAreas()>0))
room=addWorldRoomsLiberally(rooms,A2);
}
}
}
final List<Room> responseSet = returnResponse(rooms,room);
return responseSet;
}
@Override
public boolean isHere(final CMObject E2, final Room here)
{
if(E2==null)
return false;
else
if(E2==here)
return true;
else
if((E2 instanceof MOB)
&&(((MOB)E2).location()==here))
return true;
else
if((E2 instanceof Item)
&&(((Item)E2).owner()==here))
return true;
else
if((E2 instanceof Item)
&&(((Item)E2).owner()!=null)
&&(((Item)E2).owner() instanceof MOB)
&&(((MOB)((Item)E2).owner()).location()==here))
return true;
else
if(E2 instanceof Exit)
{
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
if(here.getRawExit(d)==E2)
return true;
}
return false;
}
@Override
public boolean isHere(final CMObject E2, final Area here)
{
if(E2==null)
return false;
else
if(E2==here)
return true;
else
if(E2 instanceof Room)
return ((Room)E2).getArea()==here;
else
if(E2 instanceof MOB)
return isHere(((MOB)E2).location(),here);
else
if(E2 instanceof Item)
return isHere(((Item)E2).owner(),here);
return false;
}
protected PairVector<MOB,String> getAllPlayersHere(final Area area, final boolean includeLocalFollowers)
{
final PairVector<MOB,String> playersHere=new PairVector<MOB,String>();
MOB M=null;
Room R=null;
for(final Session S : CMLib.sessions().localOnlineIterable())
{
M=S.mob();
R=(M!=null)?M.location():null;
if((R!=null)&&(R.getArea()==area)&&(M!=null))
{
playersHere.addElement(M,getExtendedRoomID(R));
if(includeLocalFollowers)
{
MOB M2=null;
final Set<MOB> H=M.getGroupMembers(new HashSet<MOB>());
for(final Iterator<MOB> i=H.iterator();i.hasNext();)
{
M2=i.next();
if((M2!=M)&&(M2.location()==R))
playersHere.addElement(M2,getExtendedRoomID(R));
}
}
}
}
return playersHere;
}
@Override
public void resetArea(final Area area)
{
final Area.State oldFlag=area.getAreaState();
area.setAreaState(Area.State.FROZEN);
final PairVector<MOB,String> playersHere=getAllPlayersHere(area,true);
final PairVector<PrivateProperty, String> propertyHere=new PairVector<PrivateProperty, String>();
for(int p=0;p<playersHere.size();p++)
{
final MOB M=playersHere.elementAt(p).first;
final Room R=M.location();
R.delInhabitant(M);
}
for(final Enumeration<Boardable> b=ships();b.hasMoreElements();)
{
final Boardable ship=b.nextElement();
final Room R=roomLocation(ship);
if((R!=null)
&&(R.getArea()==area)
&&(ship instanceof PrivateProperty)
&&(((PrivateProperty)ship).getOwnerName().length()>0)
&&(ship instanceof Item))
{
R.delItem((Item)ship);
propertyHere.add((PrivateProperty)ship,getExtendedRoomID(R));
}
}
for(final Enumeration<Room> r=area.getProperMap();r.hasMoreElements();)
resetRoom(r.nextElement());
area.fillInAreaRooms();
for(int p=0;p<playersHere.size();p++)
{
final MOB M=playersHere.elementAt(p).first;
Room R=getRoom(playersHere.elementAt(p).second);
if(R==null)
R=M.getStartRoom();
if(R==null)
R=getStartRoom(M);
if(R!=null)
R.bringMobHere(M,false);
}
for(int p=0;p<propertyHere.size();p++)
{
final PrivateProperty P=propertyHere.elementAt(p).first;
Room R=getRoom(propertyHere.elementAt(p).second);
if((R==null)||(R.amDestroyed()))
R=getSafeRoomToMovePropertyTo((R==null)?area.getRandomProperRoom():R,P);
if(R!=null)
R.moveItemTo((Item)P);
}
CMLib.database().DBReadAreaData(area);
area.setAreaState(oldFlag);
}
@Override
public boolean hasASky(final Room room)
{
if((room==null)
||(room.domainType()==Room.DOMAIN_OUTDOORS_UNDERWATER)
||((room.domainType()&Room.INDOORS)>0))
return false;
return true;
}
@Override
public void registerWorldObjectDestroyed(Area area, final Room room, final CMObject o)
{
if(o instanceof Deity)
delDeity((Deity)o);
if((o instanceof Boardable)&&(!(o instanceof Area)))
delShip((Boardable)o);
if(o instanceof PostOffice)
CMLib.city().delPostOffice((PostOffice)o);
if(o instanceof Librarian)
CMLib.city().delLibrary((Librarian)o);
if(o instanceof Banker)
CMLib.city().delBank((Banker)o);
if(o instanceof Auctioneer)
CMLib.city().delAuctionHouse((Auctioneer)o);
if(o instanceof PhysicalAgent)
{
final PhysicalAgent AE=(PhysicalAgent)o;
if((area == null) && (room!=null))
area = room.getArea();
if(area == null)
area =getStartArea(AE);
delScriptHost(area, AE);
}
}
@Override
public void registerWorldObjectLoaded(Area area, Room room, final CMObject o)
{
if(o instanceof Deity)
addDeity((Deity)o);
if(o instanceof Boardable)
addShip((Boardable)o);
if(o instanceof PostOffice)
CMLib.city().addPostOffice((PostOffice)o);
if(o instanceof Banker)
CMLib.city().addBank((Banker)o);
if(o instanceof Librarian)
CMLib.city().addLibrary((Librarian)o);
if(o instanceof Auctioneer)
CMLib.city().addAuctionHouse((Auctioneer)o);
if(o instanceof PhysicalAgent)
{
final PhysicalAgent AE=(PhysicalAgent)o;
if(room == null)
room = getStartRoom(AE);
if((area == null) && (room!=null))
area = room.getArea();
if(area == null)
area = getStartArea(AE);
addScriptHost(area, room, AE);
if(o instanceof MOB)
{
for(final Enumeration<Item> i=((MOB)o).items();i.hasMoreElements();)
addScriptHost(area, room, i.nextElement());
}
}
}
protected void cleanScriptHosts(final SLinkedList<LocatedPair> hosts, final PhysicalAgent oneToDel, final boolean fullCleaning)
{
PhysicalAgent PA;
for (final LocatedPair W : hosts)
{
if(W==null)
hosts.remove(W);
else
{
PA=W.obj();
if((PA==null)
||(PA==oneToDel)
||(PA.amDestroyed())
||((fullCleaning)&&(!isAQualifyingScriptHost(PA))))
hosts.remove(W);
}
}
}
protected boolean isAQualifyingScriptHost(final PhysicalAgent host)
{
if(host==null)
return false;
for(final Enumeration<Behavior> e = host.behaviors();e.hasMoreElements();)
{
final Behavior B=e.nextElement();
if((B!=null) && B.isSavable() && (B instanceof ScriptingEngine))
return true;
}
for(final Enumeration<ScriptingEngine> e = host.scripts();e.hasMoreElements();)
{
final ScriptingEngine SE=e.nextElement();
if((SE!=null) && SE.isSavable())
return true;
}
return false;
}
protected boolean isAScriptHost(final Area area, final PhysicalAgent host)
{
if(area == null)
return false;
return isAScriptHost(scriptHostMap.get(area.Name()), host);
}
protected boolean isAScriptHost(final SLinkedList<LocatedPair> hosts, final PhysicalAgent host)
{
if((hosts==null)||(host==null)||(hosts.size()==0))
return false;
for (final LocatedPair W : hosts)
{
if(W.obj()==host)
return true;
}
return false;
}
protected final Object getScriptHostSemaphore(final Area area)
{
final Object semaphore;
if(SCRIPT_HOST_SEMAPHORES.containsKey(area.Name()))
semaphore=SCRIPT_HOST_SEMAPHORES.get(area.Name());
else
{
synchronized(SCRIPT_HOST_SEMAPHORES)
{
semaphore=new Object();
SCRIPT_HOST_SEMAPHORES.put(area.Name(), semaphore);
}
}
return semaphore;
}
protected void addScriptHost(final Area area, final Room room, final PhysicalAgent host)
{
if((area==null) || (host == null))
return;
if(!isAQualifyingScriptHost(host))
return;
synchronized(getScriptHostSemaphore(area))
{
SLinkedList<LocatedPair> hosts = scriptHostMap.get(area.Name());
if(hosts == null)
{
hosts=new SLinkedList<LocatedPair>();
scriptHostMap.put(area.Name(), hosts);
}
else
{
cleanScriptHosts(hosts, null, false);
if(isAScriptHost(hosts,host))
return;
}
hosts.add(new LocatedPairImpl(room, host));
}
}
protected void delScriptHost(Area area, final PhysicalAgent oneToDel)
{
if(oneToDel == null)
return;
if(area == null)
{
for(final Area A : areasList)
{
if(isAScriptHost(A,oneToDel))
{
area = A;
break;
}
}
}
if(area == null)
return;
synchronized(getScriptHostSemaphore(area))
{
final SLinkedList<LocatedPair> hosts = scriptHostMap.get(area.Name());
if(hosts==null)
return;
cleanScriptHosts(hosts, oneToDel, false);
}
}
@Override
@SuppressWarnings("unchecked")
public Enumeration<LocatedPair> scriptHosts(final Area area)
{
final LinkedList<List<LocatedPair>> V = new LinkedList<List<LocatedPair>>();
if(area == null)
{
for(final String areaKey : scriptHostMap.keySet())
V.add(scriptHostMap.get(areaKey));
}
else
{
final SLinkedList<LocatedPair> hosts = scriptHostMap.get(area.Name());
if(hosts==null)
return EmptyEnumeration.INSTANCE;
V.add(hosts);
}
if(V.size()==0)
return EmptyEnumeration.INSTANCE;
final MultiListEnumeration<LocatedPair> me=new MultiListEnumeration<LocatedPair>(V,true);
return new Enumeration<LocatedPair>()
{
@Override
public boolean hasMoreElements()
{
return me.hasMoreElements();
}
@Override
public LocatedPair nextElement()
{
final LocatedPair W = me.nextElement();
final PhysicalAgent E = W.obj();
if(((E==null) || (E.amDestroyed())) && hasMoreElements())
return nextElement();
return W;
}
};
}
@Override
public boolean activate()
{
if(serviceClient==null)
{
name="THMap"+Thread.currentThread().getThreadGroup().getName().charAt(0);
serviceClient=CMLib.threads().startTickDown(this, Tickable.TICKID_SUPPORT|Tickable.TICKID_SOLITARYMASK, MudHost.TIME_SAVETHREAD_SLEEP, 1);
}
return true;
}
@Override
public boolean tick(final Tickable ticking, final int tickID)
{
if((!CMSecurity.isDisabled(CMSecurity.DisFlag.SAVETHREAD))
&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.MAPTHREAD))
&&(tickStatus == Tickable.STATUS_NOT))
{
try
{
tickStatus=Tickable.STATUS_ALIVE;
isDebugging=CMSecurity.isDebugging(DbgFlag.MAPTHREAD);
if(checkDatabase())
roomMaintSweep();
setThreadStatus(serviceClient,"saving props");
Resources.savePropResources();
}
finally
{
tickStatus=Tickable.STATUS_NOT;
setThreadStatus(serviceClient,"sleeping");
}
}
return true;
}
@Override
public boolean shutdown()
{
final boolean debugMem = CMSecurity.isDebugging(CMSecurity.DbgFlag.SHUTDOWN);
for(final Enumeration<Area> a=areasList.elements();a.hasMoreElements();)
{
try
{
final Area A = a.nextElement();
if(A!=null)
{
CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down Map area '"+A.Name()+"'...");
final LinkedList<Room> rooms=new LinkedList<Room>();
for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();)
{
try
{
final Room R=r.nextElement();
if(R!=null)
rooms.add(R);
}
catch(final Exception e)
{
}
}
for(final Iterator<Room> r=rooms.iterator();r.hasNext();)
{
try
{
final Room R=r.next();
A.delProperRoom(R);
R.destroy();
}
catch(final Exception e)
{
}
}
}
if(debugMem)
{
try
{
Object obj = new Object();
final WeakReference<Object> ref = new WeakReference<Object>(obj);
obj = null;
System.gc();
System.runFinalization();
while(ref.get() != null)
{
System.gc();
}
Thread.sleep(3000);
}
catch (final Exception e)
{
}
final long free=Runtime.getRuntime().freeMemory()/1024;
final long total=Runtime.getRuntime().totalMemory()/1024;
if(A!=null)
Log.debugOut("Memory: CMMap: "+A.Name()+": "+(total-free)+"/"+total);
}
}
catch (final Exception e)
{
}
}
areasList.clear();
deitiesList.clear();
shipList.clear();
globalHandlers.clear();
if(CMLib.threads().isTicking(this, TICKID_SUPPORT|Tickable.TICKID_SOLITARYMASK))
{
CMLib.threads().deleteTick(this, TICKID_SUPPORT|Tickable.TICKID_SOLITARYMASK);
serviceClient=null;
}
return true;
}
public void roomMaintSweep()
{
final boolean corpsesOnly=CMSecurity.isSaveFlag(CMSecurity.SaveFlag.ROOMITEMS);
final boolean noMobs=CMSecurity.isSaveFlag(CMSecurity.SaveFlag.ROOMMOBS);
setThreadStatus(serviceClient,"expiration sweep");
final long currentTime=System.currentTimeMillis();
final boolean debug=CMSecurity.isDebugging(CMSecurity.DbgFlag.VACUUM);
final MOB expireM=getFactoryMOB(null);
try
{
final List<Environmental> stuffToGo=new LinkedList<Environmental>();
final List<Room> roomsToGo=new LinkedList<Room>();
final CMMsg expireMsg=CMClass.getMsg(expireM,null,null,CMMsg.MSG_EXPIRE,null);
for(final Enumeration<Room> r=roomsFilled();r.hasMoreElements();)
{
final Room R=r.nextElement();
expireM.setLocation(R);
expireMsg.setTarget(R);
if((R.expirationDate()!=0)
&&(currentTime>R.expirationDate())
&&(R.okMessage(R,expireMsg)))
roomsToGo.add(R);
else
if(!R.amDestroyed())
{
stuffToGo.clear();
for(int i=0;i<R.numItems();i++)
{
final Item I=R.getItem(i);
if((I!=null)
&&((!corpsesOnly)||(I instanceof DeadBody))
&&(I.expirationDate()!=0)
&&(I.owner()==R)
&&(currentTime>I.expirationDate()))
stuffToGo.add(I);
}
if(!noMobs)
{
for(int i=0;i<R.numInhabitants();i++)
{
final MOB M=R.fetchInhabitant(i);
if((M!=null)
&&(M.expirationDate()!=0)
&&(currentTime>M.expirationDate()))
stuffToGo.add(M);
}
}
}
if(stuffToGo.size()>0)
{
boolean success=true;
for(final Environmental E : stuffToGo)
{
//setThreadStatus(serviceClient,"expiring "+E.Name()); // just too much -- ms count here
expireMsg.setTarget(E);
if(R.okMessage(expireM,expireMsg))
R.sendOthers(expireM,expireMsg);
else
success=false;
if(debug)
Log.sysOut("UTILITHREAD","Expired "+E.Name()+" in "+getExtendedRoomID(R)+": "+success);
}
stuffToGo.clear();
}
}
for(final Room R : roomsToGo)
{
expireM.setLocation(R);
expireMsg.setTarget(R);
setThreadStatus(serviceClient,"expirating room "+getExtendedRoomID(R));
if(debug)
{
String roomID=getExtendedRoomID(R);
if(roomID.length()==0)
roomID="(unassigned grid room, probably in the air)";
if(debug)
Log.sysOut("UTILITHREAD","Expired "+roomID+".");
}
R.sendOthers(expireM,expireMsg);
}
}
catch(final java.util.NoSuchElementException e)
{
}
setThreadStatus(serviceClient,"title sweeping");
final LegalLibrary law=CMLib.law();
final Set<String> playerList=new TreeSet<String>();
try
{
final Set<LandTitle> titlesDone = new HashSet<LandTitle>();
for(final Enumeration<Area> a=areas();a.hasMoreElements();)
{
final Area A=a.nextElement();
if(A.numEffects()>0)
{
final LandTitle T=law.getLandTitle(A);
if((T!=null)
&&(!titlesDone.contains(T)))
{
T.updateLot(playerList);
titlesDone.add(T);
}
}
}
for(final Enumeration<Room> r=rooms();r.hasMoreElements();)
{
final Room R=r.nextElement();
// roomid > 0? these are unfilled...
if(R.numEffects()>0)
{
for(final Enumeration<Ability> a=R.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if(A instanceof LandTitle)
{
final LandTitle T=(LandTitle)A;
if(!titlesDone.contains(T))
{
T.updateLot(playerList);
titlesDone.add(T);
}
}
}
}
}
}
catch(final NoSuchElementException nse)
{
}
setThreadStatus(serviceClient,"cleaning scripts");
for(final String areaKey : scriptHostMap.keySet())
cleanScriptHosts(scriptHostMap.get(areaKey), null, true);
final long lastDateTime=System.currentTimeMillis()-(5*TimeManager.MILI_MINUTE);
setThreadStatus(serviceClient,"checking");
try
{
for(final Enumeration<Room> r=roomsFilled();r.hasMoreElements();)
{
final Room R=r.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
final MOB mob=R.fetchInhabitant(m);
if(mob == null)
continue;
if(mob.amDestroyed())
{
R.delInhabitant(mob);
continue;
}
if((mob.lastTickedDateTime()>0)
&&(mob.lastTickedDateTime()<lastDateTime))
{
final boolean ticked=CMLib.threads().isTicking(mob,Tickable.TICKID_MOB);
final boolean isDead=mob.amDead();
final Room startR=mob.getStartRoom();
final String wasFrom=(startR!=null)?startR.roomID():"NULL";
if(!ticked)
{
if(!mob.isPlayer())
{
if(ticked)
{
// we have a dead group.. let the group handler deal with it.
Log.errOut(serviceClient.getName(),mob.name()+" in room "+getDescriptiveExtendedRoomID(R)
+" unticked in dead group (Home="+wasFrom+") since: "+CMLib.time().date2String(mob.lastTickedDateTime())+".");
continue;
}
else
{
Log.errOut(serviceClient.getName(),mob.name()+" in room "+getDescriptiveExtendedRoomID(R)
+" unticked (is ticking="+(ticked)+", dead="+isDead+", Home="+wasFrom+") since: "+CMLib.time().date2String(mob.lastTickedDateTime())+"."+(ticked?"":" This mob has been destroyed. May he rest in peace."));
mob.destroy();
}
}
else
{
Log.errOut(serviceClient.getName(),"Player "+mob.name()+" in room "+getDescriptiveExtendedRoomID(R)
+" unticked (is ticking="+(ticked)+", dead="+isDead+", Home="+wasFrom+") since: "+CMLib.time().date2String(mob.lastTickedDateTime())+"."+(ticked?"":" This mob has been put aside."));
}
R.delInhabitant(mob);//keeps it from happening again.
}
}
}
}
}
catch(final java.util.NoSuchElementException e)
{
}
finally
{
if(expireM!=null)
expireM.destroy();
}
}
protected final static char[] cmfsFilenameifyChars=new char[]{'/','\\',' '};
protected String cmfsFilenameify(final String str)
{
return CMStrings.replaceAllofAny(str, cmfsFilenameifyChars, '_').toLowerCase().trim();
}
// this is a beautiful idea, but im scared of the memory of all the final refs
protected void addMapStatFiles(final List<CMFile.CMVFSFile> rootFiles, final Room R, final Environmental E, final CMFile.CMVFSDir root)
{
rootFiles.add(new CMFile.CMVFSDir(root,root.getPath()+"stats/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
final String[] stats=E.getStatCodes();
final String oldName=E.Name();
for (final String statName : stats)
{
final String statValue=E.getStat(statName);
myFiles.add(new CMFile.CMVFSFile(this.getPath()+statName,256,System.currentTimeMillis(),"SYS")
{
@Override
public int getMaskBits(final MOB accessor)
{
if(accessor==null)
return this.mask;
if((E instanceof Area)&&(CMSecurity.isAllowed(accessor,((Area)E).getRandomProperRoom(),CMSecurity.SecFlag.CMDAREAS)))
return this.mask;
else
if(CMSecurity.isAllowed(accessor,R,CMSecurity.SecFlag.CMDROOMS))
return this.mask;
else
if((E instanceof MOB) && CMSecurity.isAllowed(accessor,R,CMSecurity.SecFlag.CMDMOBS))
return this.mask;
else
if((E instanceof Item) && CMSecurity.isAllowed(accessor,R,CMSecurity.SecFlag.CMDITEMS))
return this.mask;
return this.mask|48;
}
@Override
public Object readData()
{
return statValue;
}
@Override
public void saveData(final String filename, final int vfsBits, final String author, final Object O)
{
E.setStat(statName, O.toString());
if(E instanceof Area)
CMLib.database().DBUpdateArea(oldName, (Area)E);
else
if(E instanceof Room)
CMLib.database().DBUpdateRoom((Room)E);
else
if(E instanceof MOB)
CMLib.database().DBUpdateMOB(R.roomID(), (MOB)E);
else
if(E instanceof Item)
CMLib.database().DBUpdateItem(R.roomID(), (Item)E);
}
});
}
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
});
}
@Override
public CMFile.CMVFSDir getMapRoot(final CMFile.CMVFSDir root)
{
return new CMFile.CMVFSDir(root,root.getPath()+"map/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>(numAreas());
for(final Enumeration<Area> a=areas();a.hasMoreElements();)
{
final Area A=a.nextElement();
myFiles.add(new CMFile.CMVFSFile(this.getPath()+cmfsFilenameify(A.Name())+".cmare",48,System.currentTimeMillis(),"SYS")
{
@Override
public Object readData()
{
return CMLib.coffeeMaker().getAreaXML(A, null, null, null, true);
}
});
myFiles.add(new CMFile.CMVFSDir(this,this.getPath()+cmfsFilenameify(A.Name())+"/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
for(final Enumeration<Room> r=A.getFilledProperMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
if(R.roomID().length()>0)
{
String roomID=R.roomID();
if(roomID.startsWith(A.Name()+"#"))
roomID=roomID.substring(A.Name().length()+1);
myFiles.add(new CMFile.CMVFSFile(this.getPath()+cmfsFilenameify(R.roomID())+".cmare",48,System.currentTimeMillis(),"SYS")
{
@Override
public Object readData()
{
return CMLib.coffeeMaker().getRoomXML(R, null, null, true);
}
});
myFiles.add(new CMFile.CMVFSDir(this,this.getPath()+cmfsFilenameify(roomID).toLowerCase()+"/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
myFiles.add(new CMFile.CMVFSFile(this.getPath()+"items.cmare",48,System.currentTimeMillis(),"SYS")
{
@Override
public Object readData()
{
return CMLib.coffeeMaker().getRoomItems(R, new TreeMap<String,List<Item>>(), null, null);
}
});
myFiles.add(new CMFile.CMVFSFile(this.path+"mobs.cmare",48,System.currentTimeMillis(),"SYS")
{
@Override
public Object readData()
{
return CMLib.coffeeMaker().getRoomMobs(R, null, null, new TreeMap<String,List<MOB>>());
}
});
myFiles.add(new CMFile.CMVFSDir(this,this.path+"mobs/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
final Room R2=CMLib.coffeeMaker().makeNewRoomContent(R, false);
if(R2!=null)
{
for(int i=0;i<R2.numInhabitants();i++)
{
final MOB M=R2.fetchInhabitant(i);
myFiles.add(new CMFile.CMVFSFile(this.path+cmfsFilenameify(R2.getContextName(M))+".cmare",48,System.currentTimeMillis(),"SYS")
{
@Override
public Object readData()
{
return CMLib.coffeeMaker().getMobXML(M);
}
});
myFiles.add(new CMFile.CMVFSDir(this,this.path+cmfsFilenameify(R2.getContextName(M))+"/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
addMapStatFiles(myFiles,R,M,this);
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
});
}
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
}
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
});
myFiles.add(new CMFile.CMVFSDir(this,this.path+"items/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
final Room R2=CMLib.coffeeMaker().makeNewRoomContent(R, false);
if(R2 != null)
{
for(int i=0;i<R2.numItems();i++)
{
final Item I=R2.getItem(i);
myFiles.add(new CMFile.CMVFSFile(this.path+cmfsFilenameify(R2.getContextName(I))+".cmare",48,System.currentTimeMillis(),"SYS")
{
@Override
public Object readData()
{
return CMLib.coffeeMaker().getItemXML(I);
}
});
myFiles.add(new CMFile.CMVFSDir(this,this.path+cmfsFilenameify(R2.getContextName(I))+"/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
addMapStatFiles(myFiles,R,I,this);
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
});
}
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
return new CMFile.CMVFSFile[0];
}
});
addMapStatFiles(myFiles,R,R,this);
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
});
}
}
addMapStatFiles(myFiles,null,A,this);
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
});
}
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
};
}
}
| com/planet_ink/coffee_mud/Libraries/CMMap.java | package com.planet_ink.coffee_mud.Libraries;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.CMLib.Library;
import com.planet_ink.coffee_mud.core.CMSecurity.DbgFlag;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.core.collections.MultiEnumeration.MultiEnumeratorBuilder;
import com.planet_ink.coffee_mud.core.interfaces.BoundedObject;
import com.planet_ink.coffee_mud.core.interfaces.BoundedObject.BoundedCube;
import com.planet_ink.coffee_mud.core.interfaces.LandTitle;
import com.planet_ink.coffee_mud.core.interfaces.MsgListener;
import com.planet_ink.coffee_mud.core.interfaces.PrivateProperty;
import com.planet_ink.coffee_mud.core.interfaces.SpaceObject;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.ShipDirectional.ShipDir;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.*;
import java.util.Map.Entry;
/*
Copyright 2001-2022 Bo Zimmerman
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.
*/
public class CMMap extends StdLibrary implements WorldMap
{
@Override
public String ID()
{
return "CMMap";
}
protected static MOB deityStandIn = null;
protected long lastVReset = 0;
protected CMNSortSVec<Area> areasList = new CMNSortSVec<Area>();
protected CMNSortSVec<Deity> deitiesList = new CMNSortSVec<Deity>();
protected List<Boardable> shipList = new SVector<Boardable>();
protected Map<String, Object> SCRIPT_HOST_SEMAPHORES = new Hashtable<String, Object>();
protected static final Comparator<Area> areaComparator = new Comparator<Area>()
{
@Override
public int compare(final Area o1, final Area o2)
{
if(o1==null)
return (o2==null)?0:-1;
return o1.Name().compareToIgnoreCase(o2.Name());
}
};
public Map<Integer,List<WeakReference<MsgListener>>>
globalHandlers = new SHashtable<Integer,List<WeakReference<MsgListener>>>();
public Map<String,SLinkedList<LocatedPair>>
scriptHostMap = new STreeMap<String,SLinkedList<LocatedPair>>();
private static final long EXPIRE_1MIN = 1*60*1000;
private static final long EXPIRE_5MINS = 5*60*1000;
private static final long EXPIRE_10MINS = 10*60*1000;
private static final long EXPIRE_20MINS = 20*60*1000;
private static final long EXPIRE_30MINS = 30*60*1000;
private static final long EXPIRE_1HOUR = 60*60*1000;
private static class LocatedPairImpl implements LocatedPair
{
final WeakReference<Room> roomW;
final WeakReference<PhysicalAgent> objW;
private LocatedPairImpl(final Room room, final PhysicalAgent host)
{
roomW = new WeakReference<Room>(room);
objW = new WeakReference<PhysicalAgent>(host);
}
@Override
public Room room()
{
return roomW.get();
}
@Override
public PhysicalAgent obj()
{
return objW.get();
}
}
private static Filterer<Area> mundaneAreaFilter=new Filterer<Area>()
{
@Override
public boolean passesFilter(final Area obj)
{
return !(obj instanceof SpaceObject);
}
};
private static Filterer<Area> topLevelAreaFilter=new Filterer<Area>()
{
@Override
public boolean passesFilter(final Area obj)
{
return ! obj.getParents().hasMoreElements();
}
};
protected int getGlobalIndex(final List<Environmental> list, final String name)
{
if(list.size()==0)
return -1;
int start=0;
int end=list.size()-1;
while(start<=end)
{
final int mid=(end+start)/2;
try
{
final int comp=list.get(mid).Name().compareToIgnoreCase(name);
if(comp==0)
return mid;
else
if(comp>0)
end=mid-1;
else
start=mid+1;
}
catch(final java.lang.ArrayIndexOutOfBoundsException e)
{
start=0;
end=list.size()-1;
}
}
return -1;
}
@Override
public void renamedArea(final Area theA)
{
areasList.reSort(theA);
}
// areas
@Override
public int numAreas()
{
return areasList.size();
}
@Override
public void addArea(final Area newOne)
{
areasList.add(newOne);
if((newOne instanceof SpaceObject)&&(!CMLib.space().isObjectInSpace((SpaceObject)newOne)))
CMLib.space().addObjectToSpace((SpaceObject)newOne);
}
@Override
public void delArea(final Area oneToDel)
{
areasList.remove(oneToDel);
if((oneToDel instanceof SpaceObject)&&(CMLib.space().isObjectInSpace((SpaceObject)oneToDel)))
CMLib.space().delObjectInSpace((SpaceObject)oneToDel);
Resources.removeResource("SYSTEM_AREA_FINDER_CACHE");
}
@Override
public Area getModelArea(final Area A)
{
if(A!=null)
{
if(CMath.bset(A.flags(),Area.FLAG_INSTANCE_CHILD))
{
final int x=A.Name().indexOf('_');
if((x>0)
&&(CMath.isInteger(A.Name().substring(0,x))))
{
final Area A2=getArea(A.Name().substring(x+1));
if(A2!=null)
return A2;
}
}
}
return A;
}
@Override
public Area getArea(final String calledThis)
{
final Map<String,Area> finder=getAreaFinder();
Area A=finder.get(calledThis.toLowerCase());
if((A!=null)&&(!A.amDestroyed()))
return A;
final SearchIDList<Area> list;
synchronized(areasList)
{
list = areasList;
}
A=list.find(calledThis);
if((A!=null)&&(!A.amDestroyed()))
{
if(!CMProps.getBoolVar(CMProps.Bool.MAPFINDSNOCACHE))
finder.put(calledThis.toLowerCase(), A);
return A;
}
return null;
}
@Override
public Area findAreaStartsWith(final String calledThis)
{
final boolean disableCaching=CMProps.getBoolVar(CMProps.Bool.MAPFINDSNOCACHE);
Area A=getArea(calledThis);
if(A!=null)
return A;
final Map<String,Area> finder=getAreaFinder();
A=finder.get(calledThis.toLowerCase());
if((A!=null)&&(!A.amDestroyed()))
return A;
for(final Enumeration<Area> a=areas();a.hasMoreElements();)
{
A=a.nextElement();
if(A.Name().toUpperCase().startsWith(calledThis))
{
if(!disableCaching)
finder.put(calledThis.toLowerCase(), A);
return A;
}
}
return null;
}
@Override
public Area findArea(final String calledThis)
{
final boolean disableCaching=CMProps.getBoolVar(CMProps.Bool.MAPFINDSNOCACHE);
Area A=findAreaStartsWith(calledThis);
if(A!=null)
return A;
final Map<String,Area> finder=getAreaFinder();
A=finder.get(calledThis.toLowerCase());
if((A!=null)&&(!A.amDestroyed()))
return A;
for(final Enumeration<Area> a=areas();a.hasMoreElements();)
{
A=a.nextElement();
if(CMLib.english().containsString(A.Name(),calledThis))
{
if(!disableCaching)
finder.put(calledThis.toLowerCase(), A);
return A;
}
}
return null;
}
@Override
public Enumeration<Area> areas()
{
return new IteratorEnumeration<Area>(areasList.iterator());
}
@Override
public Enumeration<Area> areasPlusShips()
{
final MultiEnumeration<Area> m=new MultiEnumeration<Area>(new IteratorEnumeration<Area>(areasList.iterator()));
m.addEnumeration(shipAreaEnumerator(null));
return m;
}
@Override
public Enumeration<Area> mundaneAreas()
{
return new FilteredEnumeration<Area>(areas(),mundaneAreaFilter);
}
@Override
public Enumeration<Area> topAreas()
{
return new FilteredEnumeration<Area>(areas(),topLevelAreaFilter);
}
@Override
public Enumeration<String> roomIDs()
{
return new Enumeration<String>()
{
private volatile Enumeration<String> roomIDEnumerator=null;
private volatile Enumeration<Area> areaEnumerator=areasPlusShips();
@Override
public boolean hasMoreElements()
{
boolean hasMore = (roomIDEnumerator != null) && roomIDEnumerator.hasMoreElements();
while(!hasMore)
{
if((areaEnumerator == null)||(!areaEnumerator.hasMoreElements()))
{
roomIDEnumerator=null;
areaEnumerator = null;
return false;
}
final Area A=areaEnumerator.nextElement();
roomIDEnumerator=A.getProperRoomnumbers().getRoomIDs();
hasMore = (roomIDEnumerator != null) && roomIDEnumerator.hasMoreElements();
}
return hasMore;
}
@Override
public String nextElement()
{
return hasMoreElements() ? (String) roomIDEnumerator.nextElement() : null;
}
};
}
@Override
public Area getFirstArea()
{
if (areas().hasMoreElements())
return areas().nextElement();
return null;
}
@Override
public Area getDefaultParentArea()
{
final String defaultParentAreaName=CMProps.getVar(CMProps.Str.DEFAULTPARENTAREA);
if((defaultParentAreaName!=null)&&(defaultParentAreaName.trim().length()>0))
return getArea(defaultParentAreaName.trim());
return null;
}
@Override
public Area getRandomArea()
{
Area A=null;
while((numAreas()>0)&&(A==null))
{
try
{
A=areasList.get(CMLib.dice().roll(1,numAreas(),-1));
}
catch(final ArrayIndexOutOfBoundsException e)
{
}
}
return A;
}
@Override
public void addGlobalHandler(final MsgListener E, final int category)
{
if(E==null)
return;
List<WeakReference<MsgListener>> V=globalHandlers.get(Integer.valueOf(category));
if(V==null)
{
V=new SLinkedList<WeakReference<MsgListener>>();
globalHandlers.put(Integer.valueOf(category),V);
}
synchronized(V)
{
for (final WeakReference<MsgListener> W : V)
{
if(W.get()==E)
return;
}
V.add(new WeakReference<MsgListener>(E));
}
}
@Override
public void delGlobalHandler(final MsgListener E, final int category)
{
final List<WeakReference<MsgListener>> V=globalHandlers.get(Integer.valueOf(category));
if((E==null)||(V==null))
return;
synchronized(V)
{
for (final WeakReference<MsgListener> W : V)
{
if(W.get()==E)
V.remove(W);
}
}
}
@Override
public MOB deity()
{
if(deities().hasMoreElements())
return deities().nextElement();
if((deityStandIn==null)
||(deityStandIn.amDestroyed())
||(deityStandIn.amDead())
||(deityStandIn.location()==null)
||(deityStandIn.location().isInhabitant(deityStandIn)))
{
if(deityStandIn!=null)
deityStandIn.destroy();
final MOB everywhereMOB=CMClass.getMOB("StdMOB");
everywhereMOB.setName(L("god"));
everywhereMOB.setLocation(this.getRandomRoom());
deityStandIn=everywhereMOB;
}
return deityStandIn;
}
@Override
public MOB getFactoryMOBInAnyRoom()
{
return getFactoryMOB(this.getRandomRoom());
}
@Override
public MOB getFactoryMOB(final Room R)
{
final MOB everywhereMOB=CMClass.getFactoryMOB();
everywhereMOB.setName(L("somebody"));
everywhereMOB.setLocation(R);
return everywhereMOB;
}
@Override
public String createNewExit(Room from, Room room, final int direction)
{
if(direction >= from.rawDoors().length)
return "Bad direction";
if(direction >= room.rawDoors().length)
return "Bad direction";
Room opRoom=from.rawDoors()[direction];
if((opRoom!=null)&&(opRoom.roomID().length()==0))
opRoom=null;
Room reverseRoom=null;
if(opRoom!=null)
reverseRoom=opRoom.rawDoors()[Directions.getOpDirectionCode(direction)];
if((reverseRoom!=null)&&(reverseRoom==from))
return "Opposite room already exists and heads this way. One-way link created.";
Exit thisExit=null;
synchronized(CMClass.getSync("SYNC"+from.roomID()))
{
from=getRoom(from);
if(opRoom!=null)
from.rawDoors()[direction]=null;
from.rawDoors()[direction]=room;
thisExit=from.getRawExit(direction);
if(thisExit==null)
{
thisExit=CMClass.getExit("StdOpenDoorway");
from.setRawExit(direction,thisExit);
}
CMLib.database().DBUpdateExits(from);
}
synchronized(CMClass.getSync("SYNC"+room.roomID()))
{
room=getRoom(room);
if(room.rawDoors()[Directions.getOpDirectionCode(direction)]==null)
{
room.rawDoors()[Directions.getOpDirectionCode(direction)]=from;
room.setRawExit(Directions.getOpDirectionCode(direction),thisExit);
CMLib.database().DBUpdateExits(room);
}
}
return "";
}
@Override
public int numRooms()
{
int total=0;
for(final Enumeration<Area> e=areas();e.hasMoreElements();)
total+=e.nextElement().properSize();
return total;
}
@Override
public boolean sendGlobalMessage(final MOB host, final int category, final CMMsg msg)
{
final List<WeakReference<MsgListener>> V=globalHandlers.get(Integer.valueOf(category));
if(V==null)
return true;
synchronized(V)
{
try
{
MsgListener O=null;
Environmental E=null;
for(final WeakReference<MsgListener> W : V)
{
O=W.get();
if(O instanceof Environmental)
{
E=(Environmental)O;
if(!CMLib.flags().isInTheGame(E,true))
{
if(!CMLib.flags().isInTheGame(E,false))
delGlobalHandler(E,category);
}
else
if(!E.okMessage(host,msg))
return false;
}
else
if(O!=null)
{
if(!O.okMessage(host, msg))
return false;
}
else
V.remove(W);
}
for(final WeakReference<MsgListener> W : V)
{
O=W.get();
if(O !=null)
O.executeMsg(host,msg);
}
}
catch(final java.lang.ArrayIndexOutOfBoundsException xx)
{
}
catch (final Exception x)
{
Log.errOut("CMMap", x);
}
}
return true;
}
@Override
public String getExtendedRoomID(final Room R)
{
if(R==null)
return "";
if(R.roomID().length()>0)
return R.roomID();
final Area A=R.getArea();
if(A==null)
return "";
final GridLocale GR=R.getGridParent();
if((GR!=null)&&(GR.roomID().length()>0))
return GR.getGridChildCode(R);
return R.roomID();
}
@Override
public String getDescriptiveExtendedRoomID(final Room room)
{
if(room==null)
return "";
final String roomID = getExtendedRoomID(room);
if(roomID.length()>0)
return roomID;
final GridLocale gridParentRoom=room.getGridParent();
if((gridParentRoom!=null)&&(gridParentRoom.roomID().length()==0))
{
for(int dir=0;dir<Directions.NUM_DIRECTIONS();dir++)
{
final Room attachedRoom = gridParentRoom.rawDoors()[dir];
if(attachedRoom != null)
{
final String attachedRoomID = getExtendedRoomID(attachedRoom);
if(attachedRoomID.length()>0)
return CMLib.directions().getFromCompassDirectionName(Directions.getOpDirectionCode(dir))+" "+attachedRoomID;
}
}
}
Area area=room.getArea();
if((area==null)&&(gridParentRoom!=null))
area=gridParentRoom.getArea();
if(area == null)
return "";
return area.Name()+"#?";
}
@Override
public String getApproximateExtendedRoomID(final Room room)
{
if(room==null)
return "";
Room validRoom = CMLib.tracking().getNearestValidIDRoom(room);
if(validRoom != null)
{
if((validRoom instanceof GridLocale)
&&(validRoom.roomID()!=null)
&&(validRoom.roomID().length()>0))
validRoom=((GridLocale)validRoom).getRandomGridChild();
return getExtendedRoomID(validRoom);
}
if(room.getArea()!=null)
return room.getArea().Name()+"#?";
return "";
}
@Override
public String getExtendedTwinRoomIDs(final Room R1,final Room R2)
{
final String R1s=getExtendedRoomID(R1);
final String R2s=getExtendedRoomID(R2);
if(R1s.compareTo(R2s)>0)
return R1s+"_"+R2s;
else
return R2s+"_"+R1s;
}
@Override
public Room getRoom(final Enumeration<Room> roomSet, final String calledThis)
{
try
{
if(calledThis==null)
return null;
if(calledThis.length()==0)
return null;
if(calledThis.endsWith(")"))
{
final int child=calledThis.lastIndexOf("#(");
if(child>1)
{
Room R=getRoom(roomSet,calledThis.substring(0,child));
if((R!=null)&&(R instanceof GridLocale))
{
R=((GridLocale)R).getGridChild(calledThis);
if(R!=null)
return R;
}
}
}
Room R=null;
if(roomSet==null)
{
final int x=calledThis.indexOf('#');
if(x>=0)
{
final Area A=getArea(calledThis.substring(0,x));
if(A!=null)
R=A.getRoom(calledThis);
if(R!=null)
return R;
}
for(final Enumeration<Area> e=this.areas();e.hasMoreElements();)
{
R = e.nextElement().getRoom(calledThis);
if(R!=null)
return R;
}
for(final Enumeration<Area> e=shipAreaEnumerator(null);e.hasMoreElements();)
{
R = e.nextElement().getRoom(calledThis);
if(R!=null)
return R;
}
}
else
{
for(final Enumeration<Room> e=roomSet;e.hasMoreElements();)
{
R=e.nextElement();
if(R.roomID().equalsIgnoreCase(calledThis))
return R;
}
}
}
catch (final java.util.NoSuchElementException x)
{
}
return null;
}
@Override
public List<Room> findRooms(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean displayOnly, final int timePct)
{
final Vector<Room> roomsV=new Vector<Room>();
if((srchStr.charAt(0)=='#')&&(mob!=null)&&(mob.location()!=null))
addWorldRoomsLiberally(roomsV,getRoom(mob.location().getArea().Name()+srchStr));
else
addWorldRoomsLiberally(roomsV,getRoom(srchStr));
addWorldRoomsLiberally(roomsV,findRooms(rooms,mob,srchStr,displayOnly,false,timePct));
return roomsV;
}
@Override
public Room findFirstRoom(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean displayOnly, final int timePct)
{
final Vector<Room> roomsV=new Vector<Room>();
if((srchStr.charAt(0)=='#')&&(mob!=null)&&(mob.location()!=null))
addWorldRoomsLiberally(roomsV,getRoom(mob.location().getArea().Name()+srchStr));
else
addWorldRoomsLiberally(roomsV,getRoom(srchStr));
if(roomsV.size()>0)
return roomsV.firstElement();
addWorldRoomsLiberally(roomsV,findRooms(rooms,mob,srchStr,displayOnly,true,timePct));
if(roomsV.size()>0)
return roomsV.firstElement();
return null;
}
public List<Room> findRooms(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean displayOnly, final boolean returnFirst, final int timePct)
{
final List<Room> foundRooms=new Vector<Room>();
Vector<Room> completeRooms=null;
try
{
completeRooms=new XVector<Room>(rooms);
}
catch(final Exception nse)
{
Log.errOut("CMMap",nse);
completeRooms=new Vector<Room>();
}
final long delay=Math.round(CMath.s_pct(timePct+"%") * 1000);
Enumeration<Room> enumSet;
enumSet=completeRooms.elements();
while(enumSet.hasMoreElements())
{
findRoomsByDisplay(mob,enumSet,foundRooms,srchStr,returnFirst,delay);
if((returnFirst)&&(foundRooms.size()>0))
return foundRooms;
if(enumSet.hasMoreElements()) CMLib.s_sleep(1000 - delay);
}
if(!displayOnly)
{
enumSet=completeRooms.elements();
while(enumSet.hasMoreElements())
{
findRoomsByDesc(mob,enumSet,foundRooms,srchStr,returnFirst,delay);
if((returnFirst)&&(foundRooms.size()>0))
return foundRooms;
if(enumSet.hasMoreElements()) CMLib.s_sleep(1000 - delay);
}
}
return foundRooms;
}
protected void findRoomsByDisplay(final MOB mob, final Enumeration<Room> rooms, final List<Room> foundRooms, String srchStr, final boolean returnFirst, final long maxTime)
{
final long startTime=System.currentTimeMillis();
try
{
srchStr=srchStr.toUpperCase();
final boolean useTimer=maxTime>1;
Room room;
for(;rooms.hasMoreElements();)
{
room=rooms.nextElement();
if((CMLib.english().containsString(CMStrings.removeColors(room.displayText(mob)),srchStr))
&&((mob==null)||CMLib.flags().canAccess(mob,room)))
foundRooms.add(room);
if((useTimer)&&((System.currentTimeMillis()-startTime)>maxTime))
return;
}
}
catch (final NoSuchElementException nse)
{
}
}
protected void findRoomsByDesc(final MOB mob, final Enumeration<Room> rooms, final List<Room> foundRooms, String srchStr, final boolean returnFirst, final long maxTime)
{
final long startTime=System.currentTimeMillis();
try
{
srchStr=srchStr.toUpperCase();
final boolean useTimer=maxTime>1;
for(;rooms.hasMoreElements();)
{
final Room room=rooms.nextElement();
if((CMLib.english().containsString(CMStrings.removeColors(room.description()),srchStr))
&&((mob==null)||CMLib.flags().canAccess(mob,room)))
foundRooms.add(room);
if((useTimer)&&((System.currentTimeMillis()-startTime)>maxTime))
return;
}
}
catch (final NoSuchElementException nse)
{
}
}
@Override
public List<MOB> findInhabitants(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
return findInhabitants(rooms,mob,srchStr,false,timePct);
}
@Override
public MOB findFirstInhabitant(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
final List<MOB> found=findInhabitants(rooms,mob,srchStr,true,timePct);
if(found.size()>0)
return found.get(0);
return null;
}
public List<MOB> findInhabitants(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean returnFirst, final int timePct)
{
final Vector<MOB> found=new Vector<MOB>();
long delay=Math.round(CMath.s_pct(timePct+"%") * 1000);
if(delay>1000)
delay=1000;
final boolean useTimer = delay>1;
final boolean allRoomsAllowed=(mob==null);
long startTime=System.currentTimeMillis();
Room room;
for(;rooms.hasMoreElements();)
{
room=rooms.nextElement();
if((room != null) && (allRoomsAllowed || CMLib.flags().canAccess(mob,room)))
{
found.addAll(room.fetchInhabitants(srchStr));
if((returnFirst)&&(found.size()>0))
return found;
}
if((useTimer)&&((System.currentTimeMillis()-startTime)>delay))
{
CMLib.s_sleep(1000 - delay);
startTime=System.currentTimeMillis();
}
}
return found;
}
@Override
public List<MOB> findInhabitantsFavorExact(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean returnFirst, final int timePct)
{
final Vector<MOB> found=new Vector<MOB>();
final Vector<MOB> exact=new Vector<MOB>();
long delay=Math.round(CMath.s_pct(timePct+"%") * 1000);
if(delay>1000)
delay=1000;
final boolean useTimer = delay>1;
final boolean allRoomsAllowed=(mob==null);
long startTime=System.currentTimeMillis();
Room room;
for(;rooms.hasMoreElements();)
{
room=rooms.nextElement();
if((room != null) && (allRoomsAllowed || CMLib.flags().canAccess(mob,room)))
{
final MOB M=room.fetchInhabitantExact(srchStr);
if(M!=null)
{
exact.add(M);
if((returnFirst)&&(exact.size()>0))
return exact;
}
found.addAll(room.fetchInhabitants(srchStr));
}
if((useTimer)&&((System.currentTimeMillis()-startTime)>delay))
{
CMLib.s_sleep(1000 - delay);
startTime=System.currentTimeMillis();
}
}
if(exact.size()>0)
return exact;
if((returnFirst)&&(found.size()>0))
{
exact.add(found.get(0));
return exact;
}
return found;
}
@Override
public List<Item> findInventory(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
return findInventory(rooms,mob,srchStr,false,timePct);
}
@Override
public Item findFirstInventory(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
final List<Item> found=findInventory(rooms,mob,srchStr,true,timePct);
if(found.size()>0)
return found.get(0);
return null;
}
public List<Item> findInventory(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean returnFirst, final int timePct)
{
final List<Item> found=new Vector<Item>();
long delay=Math.round(CMath.s_pct(timePct+"%") * 1000);
if(delay>1000)
delay=1000;
final boolean useTimer = delay>1;
long startTime=System.currentTimeMillis();
MOB M;
Room room;
if(rooms==null)
{
for(final Enumeration<MOB> e=CMLib.players().players();e.hasMoreElements();)
{
M=e.nextElement();
if(M!=null)
found.addAll(M.findItems(srchStr));
if((returnFirst)&&(found.size()>0))
return found;
}
}
else
for(;rooms.hasMoreElements();)
{
room=rooms.nextElement();
if((room != null) && ((mob==null)||CMLib.flags().canAccess(mob,room)))
{
for(int m=0;m<room.numInhabitants();m++)
{
M=room.fetchInhabitant(m);
if(M!=null)
found.addAll(M.findItems(srchStr));
}
if((returnFirst)&&(found.size()>0))
return found;
}
if((useTimer)&&((System.currentTimeMillis()-startTime)>delay))
{
CMLib.s_sleep(1000 - delay);
startTime=System.currentTimeMillis();
}
}
return found;
}
@Override
public List<Environmental> findShopStock(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
return findShopStock(rooms,mob,srchStr,false,false,timePct);
}
@Override
public Environmental findFirstShopStock(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
final List<Environmental> found=findShopStock(rooms,mob,srchStr,true,false,timePct);
if(found.size()>0)
return found.get(0);
return null;
}
@Override
public List<Environmental> findShopStockers(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
return findShopStock(rooms,mob,srchStr,false,true,timePct);
}
@Override
public Environmental findFirstShopStocker(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final int timePct)
{
final List<Environmental> found=findShopStock(rooms,mob,srchStr,true,true,timePct);
if(found.size()>0)
return found.get(0);
return null;
}
public List<Environmental> findShopStock(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean returnFirst, final boolean returnStockers, final int timePct)
{
final XVector<Environmental> found=new XVector<Environmental>();
long delay=Math.round(CMath.s_pct(timePct+"%") * 1000);
if(delay>1000)
delay=1000;
final boolean useTimer = delay>1;
long startTime=System.currentTimeMillis();
MOB M=null;
Item I=null;
final HashSet<ShopKeeper> stocks=new HashSet<ShopKeeper>(1);
final HashSet<Area> areas=new HashSet<Area>();
ShopKeeper SK=null;
final boolean allRoomsAllowed=(mob==null);
if(rooms==null)
{
for(final Enumeration<MOB> e=CMLib.players().players();e.hasMoreElements();)
{
M=e.nextElement();
if(M!=null)
{
SK=CMLib.coffeeShops().getShopKeeper(M);
if((SK!=null)&&(!stocks.contains(SK)))
{
stocks.add(SK);
final Iterator<Environmental> ei=SK.getShop().getStoreInventory(srchStr);
if(ei.hasNext())
{
if(returnFirst)
return (returnStockers)?new XVector<Environmental>(M):new XVector<Environmental>(ei);
if(returnStockers)
found.add(M);
else
found.addAll(ei);
}
}
for(int i=0;i<M.numItems();i++)
{
I=M.getItem(i);
if(I!=null)
{
SK=CMLib.coffeeShops().getShopKeeper(I);
if((SK!=null)&&(!stocks.contains(SK)))
{
stocks.add(SK);
final Iterator<Environmental> ei=SK.getShop().getStoreInventory(srchStr);
if(ei.hasNext())
{
if(returnFirst)
return (returnStockers)?new XVector<Environmental>(I):new XVector<Environmental>(ei);
if(returnStockers)
found.add(I);
else
found.addAll(ei);
}
}
}
}
}
if((useTimer)&&((System.currentTimeMillis()-startTime)>delay))
{
try
{
Thread.sleep(1000 - delay);
startTime = System.currentTimeMillis();
}
catch (final Exception ex)
{
}
}
}
}
else
for(;rooms.hasMoreElements();)
{
final Room room=rooms.nextElement();
if((room != null) && (allRoomsAllowed||CMLib.flags().canAccess(mob,room)))
{
if(!areas.contains(room.getArea()))
areas.add(room.getArea());
SK=CMLib.coffeeShops().getShopKeeper(room);
if((SK!=null)&&(!stocks.contains(SK)))
{
stocks.add(SK);
final Iterator<Environmental> ei=SK.getShop().getStoreInventory(srchStr);
if(ei.hasNext())
{
if(returnFirst)
return (returnStockers)?new XVector<Environmental>(room):new XVector<Environmental>(ei);
if(returnStockers)
found.add(room);
else
found.addAll(ei);
}
}
for(int m=0;m<room.numInhabitants();m++)
{
M=room.fetchInhabitant(m);
if(M!=null)
{
SK=CMLib.coffeeShops().getShopKeeper(M);
if((SK!=null)&&(!stocks.contains(SK)))
{
stocks.add(SK);
final Iterator<Environmental> ei=SK.getShop().getStoreInventory(srchStr);
if(ei.hasNext())
{
if(returnFirst)
return (returnStockers)?new XVector<Environmental>(M):new XVector<Environmental>(ei);
if(returnStockers)
found.add(M);
else
found.addAll(ei);
}
}
}
}
for(int i=0;i<room.numItems();i++)
{
I=room.getItem(i);
if(I!=null)
{
SK=CMLib.coffeeShops().getShopKeeper(I);
if((SK!=null)&&(!stocks.contains(SK)))
{
stocks.add(SK);
final Iterator<Environmental> ei=SK.getShop().getStoreInventory(srchStr);
if(ei.hasNext())
{
if(returnFirst)
return (returnStockers)?new XVector<Environmental>(I):new XVector<Environmental>(ei);
if(returnStockers)
found.add(I);
else
found.addAll(ei);
}
}
}
}
}
if((useTimer)&&((System.currentTimeMillis()-startTime)>delay))
{
CMLib.s_sleep(1000 - delay);
startTime=System.currentTimeMillis();
}
}
for (final Area A : areas)
{
SK=CMLib.coffeeShops().getShopKeeper(A);
if((SK!=null)&&(!stocks.contains(SK)))
{
stocks.add(SK);
final Iterator<Environmental> ei=SK.getShop().getStoreInventory(srchStr);
if(ei.hasNext())
{
if(returnFirst)
return (returnStockers)?new XVector<Environmental>(A):new XVector<Environmental>(ei);
if(returnStockers)
found.add(A);
else
found.addAll(ei);
}
}
}
return found;
}
@Override
public List<Item> findRoomItems(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean anyItems, final int timePct)
{
return findRoomItems(rooms,mob,srchStr,anyItems,false,timePct);
}
@Override
public Item findFirstRoomItem(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean anyItems, final int timePct)
{
final List<Item> found=findRoomItems(rooms,mob,srchStr,anyItems,true,timePct);
if(found.size()>0)
return found.get(0);
return null;
}
protected List<Item> findRoomItems(final Enumeration<Room> rooms, final MOB mob, final String srchStr, final boolean anyItems, final boolean returnFirst, final int timePct)
{
final Vector<Item> found=new Vector<Item>(); // ultimate return value
long delay=Math.round(CMath.s_pct(timePct+"%") * 1000);
if(delay>1000)
delay=1000;
final boolean useTimer = delay>1;
long startTime=System.currentTimeMillis();
final boolean allRoomsAllowed=(mob==null);
Room room;
for(;rooms.hasMoreElements();)
{
room=rooms.nextElement();
if((room != null) && (allRoomsAllowed||CMLib.flags().canAccess(mob,room)))
{
found.addAll(anyItems?room.findItems(srchStr):room.findItems(null,srchStr));
if((returnFirst)&&(found.size()>0))
return found;
}
if((useTimer)&&((System.currentTimeMillis()-startTime)>delay))
{
CMLib.s_sleep(1000 - delay);
startTime=System.currentTimeMillis();
}
}
return found;
}
@Override
public Room getRoom(final Room room)
{
if(room==null)
return null;
if(room.amDestroyed())
return getRoom(getExtendedRoomID(room));
return room;
}
@Override
public Room getRoom(final String calledThis)
{
return getRoom(null,calledThis);
}
@Override
public Room getRoomAllHosts(final String calledThis)
{
final Room R = getRoom(null,calledThis);
if(R!=null)
return R;
for(final Enumeration<CMLibrary> pl=CMLib.libraries(CMLib.Library.MAP); pl.hasMoreElements(); )
{
final WorldMap mLib = (WorldMap)pl.nextElement();
if(mLib != this)
{
final Room R2 = mLib.getRoom(calledThis);
if(R2 != null)
return R2;
}
}
return null;
}
@Override
public Enumeration<Room> rooms()
{
return new AreasRoomsEnumerator(areasPlusShips(), false);
}
@Override
public Enumeration<Room> roomsFilled()
{
return new AreasRoomsEnumerator(areasPlusShips(), true);
}
@Override
public Enumeration<MOB> worldMobs()
{
return new RoomMobsEnumerator(roomsFilled());
}
@Override
public Enumeration<Item> worldRoomItems()
{
return new RoomItemsEnumerator(roomsFilled(), false);
}
@Override
public Enumeration<Item> worldEveryItems()
{
return new RoomItemsEnumerator(roomsFilled(),true);
}
@Override
public Room getRandomRoom()
{
Room R=null;
int numRooms=-1;
for(int i=0;i<1000 && ((R==null)&&((numRooms=numRooms())>0));i++)
{
try
{
final int which=CMLib.dice().roll(1,numRooms,-1);
int total=0;
for(final Enumeration<Area> e=areas();e.hasMoreElements();)
{
final Area A=e.nextElement();
if(which<(total+A.properSize()))
{
R = A.getRandomProperRoom();
break;
}
total+=A.properSize();
}
}
catch (final NoSuchElementException e)
{
if(i > 998)
Log.errOut(e);
}
}
return R;
}
public int numDeities()
{
return deitiesList.size();
}
protected void addDeity(final Deity newOne)
{
if (!deitiesList.contains(newOne))
deitiesList.add(newOne);
}
protected void delDeity(final Deity oneToDel)
{
if (deitiesList.contains(oneToDel))
{
//final boolean deitiesRemain = deitiesList.size()>0;
deitiesList.remove(oneToDel);
//if(deitiesRemain && ((deitiesList.size()==0)))
// Log.debugOut("**DEITIES",new Exception());
}
}
@Override
public Deity getDeity(final String calledThis)
{
if((calledThis==null)||(calledThis.length()==0))
return null;
return deitiesList.find(calledThis);
}
@Override
public Enumeration<Deity> deities()
{
return new IteratorEnumeration<Deity>(deitiesList.iterator());
}
@Override
public int numShips()
{
return shipList.size();
}
protected void addShip(final Boardable newOne)
{
if (!shipList.contains(newOne))
{
shipList.add(newOne);
final Area area=newOne.getArea();
if((area!=null)&&(area.getAreaState()==Area.State.ACTIVE))
area.setAreaState(Area.State.ACTIVE);
}
}
protected void delShip(final Boardable oneToDel)
{
if(oneToDel!=null)
{
shipList.remove(oneToDel);
final Item shipI = oneToDel.getBoardableItem();
if(shipI instanceof Boardable)
{
final Boardable boardableShipI = (Boardable)shipI;
shipList.remove(boardableShipI);
}
final Area area=oneToDel.getArea();
if(area!=null)
{
if(area instanceof Boardable)
{
final Boardable boardableShipA = (Boardable)area;
shipList.remove(boardableShipA);
}
area.setAreaState(Area.State.STOPPED);
}
}
}
@Override
public Boardable getShip(final String calledThis)
{
for (final Boardable S : shipList)
{
if (S.Name().equalsIgnoreCase(calledThis))
return S;
}
return null;
}
@Override
public Boardable findShip(final String s, final boolean exactOnly)
{
return (Boardable)CMLib.english().fetchEnvironmental(shipList, s, exactOnly);
}
@Override
public Enumeration<Boardable> ships()
{
return new IteratorEnumeration<Boardable>(shipList.iterator());
}
public Enumeration<Room> shipsRoomEnumerator(final Area inA)
{
return new Enumeration<Room>()
{
private Enumeration<Room> cur = null;
private Enumeration<Area> cA = shipAreaEnumerator(inA);
@Override
public boolean hasMoreElements()
{
boolean hasMore = (cur != null) && cur.hasMoreElements();
while(!hasMore)
{
if((cA == null)||(!cA.hasMoreElements()))
{
cur=null;
cA = null;
return false;
}
cur = cA.nextElement().getProperMap();
hasMore = (cur != null) && cur.hasMoreElements();
}
return hasMore;
}
@Override
public Room nextElement()
{
if(!hasMoreElements())
throw new NoSuchElementException();
return cur.nextElement();
}
};
}
public Enumeration<Area> shipAreaEnumerator(final Area inA)
{
return new Enumeration<Area>()
{
private volatile Area nextArea=null;
private volatile Enumeration<Boardable> shipsEnum=ships();
@Override
public boolean hasMoreElements()
{
while(nextArea == null)
{
if((shipsEnum==null)||(!shipsEnum.hasMoreElements()))
{
shipsEnum=null;
return false;
}
final Boardable ship=shipsEnum.nextElement();
if((ship!=null)&&(ship.getArea()!=null))
{
if((inA==null)||(areaLocation(ship)==inA))
nextArea=ship.getArea();
}
}
return (nextArea != null);
}
@Override
public Area nextElement()
{
if(!hasMoreElements())
throw new NoSuchElementException();
final Area A=nextArea;
this.nextArea=null;
return A;
}
};
}
@Override
public void renameRooms(final Area A, final String oldName, final List<Room> allMyDamnRooms)
{
final List<Room> onesToRenumber=new Vector<Room>();
for(Room R : allMyDamnRooms)
{
synchronized(CMClass.getSync("SYNC"+R.roomID()))
{
R=getRoom(R);
R.setArea(A);
if(oldName!=null)
{
if(R.roomID().toUpperCase().startsWith(oldName.toUpperCase()+"#"))
{
Room R2=A.getRoom(A.Name()+"#"+R.roomID().substring(oldName.length()+1));
if(R2 == null)
R2=getRoom(A.Name()+"#"+R.roomID().substring(oldName.length()+1));
if((R2==null)||(!R2.roomID().startsWith(A.Name()+"#")))
{
final String oldID=R.roomID();
R.setRoomID(A.Name()+"#"+R.roomID().substring(oldName.length()+1));
CMLib.database().DBReCreate(R,oldID);
}
else
onesToRenumber.add(R);
}
else
CMLib.database().DBUpdateRoom(R);
}
}
}
if(oldName!=null)
{
for(final Room R: onesToRenumber)
{
final String oldID=R.roomID();
R.setRoomID(A.getNewRoomID(R,-1));
CMLib.database().DBReCreate(R,oldID);
}
}
}
@Override
public int getRoomDir(final Room from, final Room to)
{
if((from==null)||(to==null))
return -1;
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
if(from.getRoomInDir(d)==to)
return d;
}
return -1;
}
@Override
public Area getTargetArea(final Room from, final Exit to)
{
final Room R=getTargetRoom(from, to);
if(R==null)
return null;
return R.getArea();
}
@Override
public Room getTargetRoom(final Room from, final Exit to)
{
if((from==null)||(to==null))
return null;
final int d=getExitDir(from, to);
if(d<0)
return null;
return from.getRoomInDir(d);
}
@Override
public int getExitDir(final Room from, final Exit to)
{
if((from==null)||(to==null))
return -1;
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
if(from.getExitInDir(d)==to)
return d;
if(from.getRawExit(d)==to)
return d;
if(from.getReverseExit(d)==to)
return d;
}
return -1;
}
@Override
public Room findConnectingRoom(final Room room)
{
if(room==null)
return null;
Room R=null;
final Vector<Room> otherChoices=new Vector<Room>();
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
R=room.getRoomInDir(d);
if(R!=null)
{
for(int d1=Directions.NUM_DIRECTIONS()-1;d1>=0;d1--)
{
if(R.getRoomInDir(d1)==room)
{
if(R.getArea()==room.getArea())
return R;
otherChoices.addElement(R);
}
}
}
}
for(final Enumeration<Room> e=rooms();e.hasMoreElements();)
{
R=e.nextElement();
if(R==room)
continue;
for(int d1=Directions.NUM_DIRECTIONS()-1;d1>=0;d1--)
{
if(R.getRoomInDir(d1)==room)
{
if(R.getArea()==room.getArea())
return R;
otherChoices.addElement(R);
}
}
}
if(otherChoices.size()>0)
return otherChoices.firstElement();
return null;
}
@Override
public boolean isClearableRoom(final Room R)
{
if((R==null)||(R.amDestroyed()))
return true;
MOB M=null;
Room sR=null;
for(int i=0;i<R.numInhabitants();i++)
{
M=R.fetchInhabitant(i);
if(M==null)
continue;
sR=M.getStartRoom();
if((sR!=null)
&&(sR != R)
&&(!sR.roomID().equals(R.roomID()))
&&(!sR.amDestroyed()))
{
CMLib.tracking().wanderAway(M, false, true);
if(M.location()==R)
return false;
}
if(M.session()!=null)
return false;
}
Item I=null;
for(int i=0;i<R.numItems();i++)
{
I=R.getItem(i);
if((I!=null)
&&((I.expirationDate()!=0)
||((I instanceof DeadBody)&&(((DeadBody)I).isPlayerCorpse()))
||((I instanceof PrivateProperty)&&(((PrivateProperty)I).getOwnerName().length()>0))))
return false;
}
for(final Enumeration<Ability> a=R.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)&&(!A.isSavable()))
return false;
}
return true;
}
@Override
public boolean explored(final Room R)
{
if((R==null)
||(CMath.bset(R.phyStats().sensesMask(),PhyStats.SENSE_ROOMUNEXPLORABLE))
||(R.getArea()==null))
return false;
return false;
}
public class AreasRoomsEnumerator implements Enumeration<Room>
{
private final Enumeration<Area> curAreaEnumeration;
private final boolean addSkys;
private volatile Enumeration<Room> curRoomEnumeration = null;
public AreasRoomsEnumerator(final Enumeration<Area> curAreaEnumeration, final boolean includeSkys)
{
addSkys = includeSkys;
this.curAreaEnumeration=curAreaEnumeration;
}
@Override
public boolean hasMoreElements()
{
boolean hasMore = (curRoomEnumeration!=null)&&(curRoomEnumeration.hasMoreElements());
while(!hasMore)
{
if((curAreaEnumeration == null)||(!curAreaEnumeration.hasMoreElements()))
{
curRoomEnumeration = null;
return false;
}
if(addSkys)
curRoomEnumeration=curAreaEnumeration.nextElement().getFilledProperMap();
else
curRoomEnumeration=curAreaEnumeration.nextElement().getProperMap();
hasMore = (curRoomEnumeration!=null)&&(curRoomEnumeration.hasMoreElements());
}
return hasMore;
}
@Override
public Room nextElement()
{
if(!hasMoreElements())
throw new NoSuchElementException();
return curRoomEnumeration.nextElement();
}
}
public class RoomMobsEnumerator implements Enumeration<MOB>
{
private final Enumeration<Room> curRoomEnumeration;
private volatile Enumeration<MOB> curMobEnumeration = null;
public RoomMobsEnumerator(final Enumeration<Room> curRoomEnumeration)
{
this.curRoomEnumeration=curRoomEnumeration;
}
@Override
public boolean hasMoreElements()
{
boolean hasMore = (curMobEnumeration!=null)&&(curMobEnumeration.hasMoreElements());
while(!hasMore)
{
if((curRoomEnumeration == null)||(!curRoomEnumeration.hasMoreElements()))
{
curMobEnumeration = null;
return false;
}
curMobEnumeration=curRoomEnumeration.nextElement().inhabitants();
hasMore = (curMobEnumeration!=null)&&(curMobEnumeration.hasMoreElements());
}
return hasMore;
}
@Override
public MOB nextElement()
{
if(!hasMoreElements())
throw new NoSuchElementException();
return curMobEnumeration.nextElement();
}
}
public class RoomItemsEnumerator implements Enumeration<Item>
{
private final Enumeration<Room> curRoomEnumeration;
private final boolean includeMobItems;
private volatile Enumeration<Item> curItemEnumeration = null;
public RoomItemsEnumerator(final Enumeration<Room> curRoomEnumeration, final boolean includeMobItems)
{
this.curRoomEnumeration=curRoomEnumeration;
this.includeMobItems=includeMobItems;
}
@Override
public boolean hasMoreElements()
{
boolean hasMore = (curItemEnumeration!=null)&&(curItemEnumeration.hasMoreElements());
while(!hasMore)
{
if((curRoomEnumeration == null)||(!curRoomEnumeration.hasMoreElements()))
{
curItemEnumeration = null;
return false;
}
if(includeMobItems)
curItemEnumeration=curRoomEnumeration.nextElement().itemsRecursive();
else
curItemEnumeration=curRoomEnumeration.nextElement().items();
hasMore = (curItemEnumeration!=null)&&(curItemEnumeration.hasMoreElements());
}
return hasMore;
}
@Override
public Item nextElement()
{
if(!hasMoreElements())
throw new NoSuchElementException();
return curItemEnumeration.nextElement();
}
}
@Override
public void obliterateMapRoom(final Room deadRoom)
{
obliterateRoom(deadRoom,null,true);
}
@Override
public void destroyRoomObject(final Room deadRoom)
{
obliterateRoom(deadRoom,null,false);
}
protected void obliterateRoom(final Room deadRoom, final List<Room> linkInRooms, final boolean includeDB)
{
for(final Enumeration<Ability> a=deadRoom.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if(A!=null)
{
A.unInvoke();
deadRoom.delEffect(A);
}
}
try
{
final List<Pair<Room,Integer>> roomsToDo=new LinkedList<Pair<Room,Integer>>();
final Enumeration<Room> r;
if(linkInRooms != null)
r=new IteratorEnumeration<Room>(linkInRooms.iterator());
else
r=rooms();
for(;r.hasMoreElements();)
{
final Room R=getRoom(r.nextElement());
if(R!=null)
{
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
final Room thatRoom=R.rawDoors()[d];
if(thatRoom==deadRoom)
roomsToDo.add(new Pair<Room,Integer>(R,Integer.valueOf(d)));
}
}
}
for(final Pair<Room,Integer> p : roomsToDo)
{
final Room R=p.first;
final int d=p.second.intValue();
synchronized(CMClass.getSync("SYNC"+R.roomID()))
{
R.rawDoors()[d]=null;
if((R.getRawExit(d)!=null)&&(R.getRawExit(d).isGeneric()))
{
final Exit GE=R.getRawExit(d);
GE.setTemporaryDoorLink(deadRoom.roomID());
}
if(includeDB)
CMLib.database().DBUpdateExits(R);
}
}
}
catch (final NoSuchElementException e)
{
}
emptyRoom(deadRoom,null,true);
deadRoom.destroy();
if(deadRoom instanceof GridLocale)
((GridLocale)deadRoom).clearGrid(null);
if(includeDB)
CMLib.database().DBDeleteRoom(deadRoom);
}
@Override
public void emptyAreaAndDestroyRooms(final Area area)
{
for(final Enumeration<Ability> a=area.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if(A!=null)
{
A.unInvoke();
area.delEffect(A);
}
}
for(final Enumeration<Room> e=area.getProperMap();e.hasMoreElements();)
{
final Room R=e.nextElement();
emptyRoom(R,null,true);
R.destroy();
}
}
@Override
public Room roomLocation(final Environmental E)
{
if(E==null)
return null;
if((E instanceof Area)&&(!((Area)E).isProperlyEmpty()))
return ((Area)E).getRandomProperRoom();
else
if(E instanceof Room)
return (Room)E;
else
if(E instanceof MOB)
return ((MOB)E).location();
else
if((E instanceof Item)&&(((Item)E).owner() instanceof Room))
return (Room)((Item)E).owner();
else
if((E instanceof Item)&&(((Item)E).owner() instanceof MOB))
return ((MOB)((Item)E).owner()).location();
else
if(E instanceof Ability)
return roomLocation(((Ability)E).affecting());
else
if(E instanceof Exit)
return roomLocation(((Exit)E).lastRoomUsedFrom(null));
return null;
}
@Override
public Area getStartArea(final Environmental E)
{
if(E instanceof Area)
return (Area)E;
final Room R=getStartRoom(E);
if(R==null)
return null;
return R.getArea();
}
@Override
public Room getStartRoom(final Environmental E)
{
if(E ==null)
return null;
if(E instanceof MOB)
return ((MOB)E).getStartRoom();
if(E instanceof Item)
{
if(((Item)E).owner() instanceof MOB)
return getStartRoom(((Item)E).owner());
if(CMLib.flags().isGettable((Item)E))
return null;
}
if(E instanceof Ability)
return getStartRoom(((Ability)E).affecting());
if((E instanceof Area)&&(!((Area)E).isProperlyEmpty()))
return ((Area)E).getRandomProperRoom();
if(E instanceof Room)
return (Room)E;
return roomLocation(E);
}
@Override
public ThreadGroup getOwnedThreadGroup(final CMObject E)
{
final Area area=areaLocation(E);
if(area != null)
{
final int theme=area.getTheme();
if((theme>0)&&(theme<Area.THEME_NAMES.length))
return CMProps.getPrivateOwner(Area.THEME_NAMES[theme]+"AREAS");
}
return null;
}
@Override
public Area areaLocation(final CMObject E)
{
if(E==null)
return null;
if(E instanceof Area)
return (Area)E;
else
if(E instanceof Room)
return ((Room)E).getArea();
else
if(E instanceof MOB)
return areaLocation(((MOB)E).location());
else
if(E instanceof Item)
return areaLocation(((Item) E).owner());
else
if((E instanceof Ability)&&(((Ability)E).affecting()!=null))
return areaLocation(((Ability)E).affecting());
else
if(E instanceof Exit)
return areaLocation(((Exit)E).lastRoomUsedFrom(null));
return null;
}
@Override
public Room getSafeRoomToMovePropertyTo(final Room room, final PrivateProperty I)
{
if(I instanceof Boardable)
{
final Room R=getRoom(((Boardable)I).getHomePortID());
if((R!=null)&&(R!=room)&&(!R.amDestroyed()))
return R;
}
if(room != null)
{
Room R=null;
if(room.getGridParent()!=null)
{
R=getRoom(room.getGridParent());
if((R!=null)&&(R!=room)&&(!R.amDestroyed())&&(R.roomID().length()>0))
return R;
}
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
R=getRoom(room.getRoomInDir(d));
if((R!=null)&&(R!=room)&&(!R.amDestroyed())&&(R.roomID().length()>0))
return R;
}
if(room.getGridParent()!=null)
{
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
R=getRoom(room.getGridParent().getRoomInDir(d));
if((R!=null)&&(R!=room)&&(!R.amDestroyed())&&(R.roomID().length()>0))
return R;
}
}
final Area A=room.getArea();
if(A!=null)
{
for(int i=0;i<A.numberOfProperIDedRooms();i++)
{
R=getRoom(A.getRandomProperRoom());
if((R!=null)&&(R!=room)&&(!R.amDestroyed())&&(R.roomID().length()>0))
return R;
}
}
}
for(int i=0;i<100;i++)
{
final Room R=getRoom(this.getRandomRoom());
if((R!=null)&&(R!=room)&&(!R.amDestroyed())&&(R.roomID().length()>0))
return R;
}
return null;
}
@Override
public void emptyRoom(final Room room, final Room toRoom, final boolean clearPlayers)
{
if(room==null)
return;
// this will empty grid rooms so that
// the code below can delete them or whatever.
if(room instanceof GridLocale)
{
for(final Iterator<Room> r=((GridLocale)room).getExistingRooms();r.hasNext();)
emptyRoom(r.next(), toRoom, clearPlayers);
}
// this will empty skys and underwater of mobs so that
// the code below can delete them or whatever.
room.clearSky();
if(toRoom != null)
{
for(final Enumeration<MOB> i=room.inhabitants();i.hasMoreElements();)
{
final MOB M=i.nextElement();
if(M!=null)
toRoom.bringMobHere(M,false);
}
}
else
if(clearPlayers)
{
for(final Enumeration<MOB> i=room.inhabitants();i.hasMoreElements();)
{
final MOB M=i.nextElement();
if((M!=null) && (M.isPlayer()))
{
Room sR=M.getStartRoom();
int attempts=1000;
while(((sR == room)||(sR==null))
&&(--attempts>0))
sR=getRandomRoom();
if((sR!=null)&&(sR!=room))
sR.bringMobHere(M,true);
else
room.delInhabitant(M);
}
}
}
for(final Enumeration<MOB> i=room.inhabitants();i.hasMoreElements();)
{
final MOB M=i.nextElement();
if((M!=null)
&&(!M.isPlayer())
&&(M.isSavable()) // this is almost certainly to protect Quest mobs, which are just about the only unsavable things.
&&((M.amFollowing()==null)||(!M.amFollowing().isPlayer())))
{
final Room startRoom = M.getStartRoom();
final Area startArea = (startRoom == null) ? null : startRoom.getArea();
if((startRoom==null)
||(startRoom==room)
||(startRoom.amDestroyed())
||(startArea==null)
||(startArea.amDestroyed())
||(startRoom.ID().length()==0))
M.destroy();
else
M.getStartRoom().bringMobHere(M,false);
}
}
Item I=null;
if(toRoom != null)
{
for(final Enumeration<Item> i=room.items();i.hasMoreElements();)
{
I=i.nextElement();
if(I!=null)
toRoom.moveItemTo(I,ItemPossessor.Expire.Player_Drop);
}
}
else
{
for(final Enumeration<Item> i=room.items();i.hasMoreElements();)
{
I=i.nextElement();
if(I != null)
{
if((I instanceof PrivateProperty)
&&((((PrivateProperty)I).getOwnerName().length()>0)))
{
final Room R=getSafeRoomToMovePropertyTo(room, (PrivateProperty)I);
if((R!=null)
&&(R!=room))
R.moveItemTo(I,ItemPossessor.Expire.Player_Drop);
}
else
I.destroy();
}
}
}
room.clearSky();
// clear debri only clears things by their start rooms, not location, so only roomid matters.
if(room.roomID().length()>0)
CMLib.threads().clearDebri(room,0);
if(room instanceof GridLocale)
{
for(final Iterator<Room> r=((GridLocale)room).getExistingRooms();r.hasNext();)
emptyRoom(r.next(), toRoom, clearPlayers);
}
}
@Override
public void obliterateMapArea(final Area A)
{
obliterateArea(A,true);
for(final Enumeration<Area> a=areas();a.hasMoreElements();)
{
final Area A2=a.nextElement();
if((A2!=null)
&&(A2.isSavable())
&&(A2.isParent(A)||A2.isChild(A)))
{
A2.removeParent(A);
A2.removeChild(A);
CMLib.database().DBUpdateArea(A2.Name(), A2);
}
}
}
@Override
public void destroyAreaObject(final Area A)
{
obliterateArea(A,false);
}
protected void obliterateArea(final Area A, final boolean includeDB)
{
if(A==null)
return;
A.setAreaState(Area.State.STOPPED);
if(A instanceof SpaceShip)
CMLib.tech().unregisterAllElectronics(CMLib.tech().getElectronicsKey(A));
final List<Room> allRooms=new LinkedList<Room>();
for(int i=0;i<2;i++)
{
for(final Enumeration<Room> e=A.getProperMap();e.hasMoreElements();)
{
final Room R=e.nextElement();
if(R!=null)
{
allRooms.add(R);
emptyRoom(R,null,false);
R.clearSky();
}
}
}
if(includeDB)
CMLib.database().DBDeleteAreaAndRooms(A);
final List<Room> linkInRooms = new LinkedList<Room>();
for(final Enumeration<Room> r=rooms();r.hasMoreElements();)
{
final Room R=getRoom(r.nextElement());
if(R!=null)
{
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
final Room thatRoom=R.rawDoors()[d];
if((thatRoom!=null)
&&(thatRoom.getArea()==A))
{
linkInRooms.add(R);
break;
}
}
}
}
for(final Room R : allRooms)
obliterateRoom(R,linkInRooms,includeDB);
delArea(A);
A.destroy(); // why not?
}
public CMMsg resetMsg=null;
@Override
public void resetRoom(final Room room)
{
resetRoom(room,false);
}
@Override
public void resetRoom(Room room, final boolean rebuildGrids)
{
if(room==null)
return;
if(room.roomID().length()==0)
return;
synchronized(CMClass.getSync("SYNC"+room.roomID()))
{
room=getRoom(room);
if((rebuildGrids)&&(room instanceof GridLocale))
((GridLocale)room).clearGrid(null);
final boolean mobile=room.getMobility();
try
{
room.toggleMobility(false);
if(resetMsg==null)
resetMsg=CMClass.getMsg(CMClass.sampleMOB(),room,CMMsg.MSG_ROOMRESET,null);
resetMsg.setTarget(room);
room.executeMsg(room,resetMsg);
if(room.isSavable())
emptyRoom(room,null,false);
for(final Enumeration<Ability> a=room.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)&&(A.canBeUninvoked()))
A.unInvoke();
}
if(room.isSavable())
{
CMLib.database().DBReReadRoomData(room);
CMLib.database().DBReadContent(room.roomID(),room,true);
}
room.startItemRejuv();
room.setResource(-1);
}
finally
{
room.toggleMobility(mobile);
}
}
}
@Override
public Room findWorldRoomLiberally(final MOB mob, final String cmd, final String srchWhatAERIPMVK, final int timePct, final long maxMillis)
{
final List<Room> rooms=findWorldRoomsLiberally(mob,cmd,srchWhatAERIPMVK,null,true,timePct, maxMillis);
if((rooms!=null)&&(rooms.size()!=0))
return rooms.get(0);
return null;
}
@Override
public List<Room> findWorldRoomsLiberally(final MOB mob, final String cmd, final String srchWhatAERIPMVK, final int timePct, final long maxMillis)
{
return findWorldRoomsLiberally(mob,cmd,srchWhatAERIPMVK,null,false,timePct,maxMillis);
}
@Override
public Room findAreaRoomLiberally(final MOB mob, final Area A,final String cmd, final String srchWhatAERIPMVK, final int timePct)
{
final List<Room> rooms=findWorldRoomsLiberally(mob,cmd,srchWhatAERIPMVK,A,true,timePct,120);
if((rooms!=null)&&(rooms.size()!=0))
return rooms.get(0);
return null;
}
@Override
public List<Room> findAreaRoomsLiberally(final MOB mob, final Area A,final String cmd, final String srchWhatAERIPMVK, final int timePct)
{
return findWorldRoomsLiberally(mob,cmd,srchWhatAERIPMVK,A,false,timePct,120);
}
protected Room addWorldRoomsLiberally(final List<Room> rooms, final List<? extends Environmental> choicesV)
{
if(choicesV==null)
return null;
if(rooms!=null)
{
for(final Environmental E : choicesV)
addWorldRoomsLiberally(rooms,roomLocation(E));
return null;
}
else
{
Room room=null;
int tries=0;
while(((room==null)||(room.roomID().length()==0))&&((++tries)<200))
room=roomLocation(choicesV.get(CMLib.dice().roll(1,choicesV.size(),-1)));
return room;
}
}
protected Room addWorldRoomsLiberally(final List<Room> rooms, final Room room)
{
if(room==null)
return null;
if(rooms!=null)
{
if(!rooms.contains(room))
rooms.add(room);
return null;
}
return room;
}
protected Room addWorldRoomsLiberally(final List<Room>rooms, final Area area)
{
if((area==null)||(area.isProperlyEmpty()))
return null;
return addWorldRoomsLiberally(rooms,area.getRandomProperRoom());
}
protected List<Room> returnResponse(final List<Room> rooms, final Room room)
{
if(rooms!=null)
return rooms;
if(room==null)
return new Vector<Room>(1);
return new XVector<Room>(room);
}
protected boolean enforceTimeLimit(final long startTime, final long maxMillis)
{
if(maxMillis<=0)
return false;
return ((System.currentTimeMillis() - startTime)) > maxMillis;
}
protected List<MOB> checkMOBCachedList(final List<MOB> list)
{
if (list != null)
{
for(final Environmental E : list)
if(E.amDestroyed())
return null;
}
return list;
}
protected List<Item> checkInvCachedList(final List<Item> list)
{
if (list != null)
{
for(final Item E : list)
if((E.amDestroyed())||(!(E.owner() instanceof MOB)))
return null;
}
return list;
}
protected List<Item> checkRoomItemCachedList(final List<Item> list)
{
if (list != null)
{
for(final Item E : list)
if((E.amDestroyed())||(!(E.owner() instanceof Room)))
return null;
}
return list;
}
@SuppressWarnings("unchecked")
public Map<String,List<MOB>> getMOBFinder()
{
Map<String,List<MOB>> finder=(Map<String,List<MOB>>)Resources.getResource("SYSTEM_MOB_FINDER_CACHE");
if(finder==null)
{
finder=new PrioritizingLimitedMap<String,List<MOB>>(10,EXPIRE_5MINS,EXPIRE_10MINS,100);
Resources.submitResource("SYSTEM_MOB_FINDER_CACHE",finder);
}
return finder;
}
@SuppressWarnings("unchecked")
public Map<String,Area> getAreaFinder()
{
Map<String,Area> finder=(Map<String,Area>)Resources.getResource("SYSTEM_AREA_FINDER_CACHE");
if(finder==null)
{
finder=new PrioritizingLimitedMap<String,Area>(50,EXPIRE_30MINS,EXPIRE_1HOUR,100);
Resources.submitResource("SYSTEM_AREA_FINDER_CACHE",finder);
}
return finder;
}
@SuppressWarnings("unchecked")
public Map<String,List<Item>> getRoomItemFinder()
{
Map<String,List<Item>> finder=(Map<String,List<Item>>)Resources.getResource("SYSTEM_RITEM_FINDER_CACHE");
if(finder==null)
{
finder=new PrioritizingLimitedMap<String,List<Item>>(10,EXPIRE_5MINS,EXPIRE_10MINS,100);
Resources.submitResource("SYSTEM_RITEM_FINDER_CACHE",finder);
}
return finder;
}
@SuppressWarnings("unchecked")
public Map<String,List<Item>> getInvItemFinder()
{
Map<String,List<Item>> finder=(Map<String,List<Item>>)Resources.getResource("SYSTEM_IITEM_FINDER_CACHE");
if(finder==null)
{
finder=new PrioritizingLimitedMap<String,List<Item>>(10,EXPIRE_1MIN,EXPIRE_10MINS,100);
Resources.submitResource("SYSTEM_IITEM_FINDER_CACHE",finder);
}
return finder;
}
@SuppressWarnings("unchecked")
public Map<String,List<Environmental>> getStockFinder()
{
Map<String,List<Environmental>> finder=(Map<String,List<Environmental>>)Resources.getResource("SYSTEM_STOCK_FINDER_CACHE");
if(finder==null)
{
finder=new PrioritizingLimitedMap<String,List<Environmental>>(10,EXPIRE_10MINS,EXPIRE_1HOUR,100);
Resources.submitResource("SYSTEM_STOCK_FINDER_CACHE",finder);
}
return finder;
}
@SuppressWarnings("unchecked")
public Map<String,List<Room>> getRoomFinder()
{
Map<String,List<Room>> finder=(Map<String,List<Room>>)Resources.getResource("SYSTEM_ROOM_FINDER_CACHE");
if(finder==null)
{
finder=new PrioritizingLimitedMap<String,List<Room>>(20,EXPIRE_20MINS,EXPIRE_1HOUR,100);
Resources.submitResource("SYSTEM_ROOM_FINDER_CACHE",finder);
}
return finder;
}
protected List<Room> findWorldRoomsLiberally(final MOB mob,
final String cmd,
final String srchWhatAERIPMVK,
Area area,
final boolean returnFirst,
final int timePct,
final long maxMillis)
{
Room room=null;
// wish this stuff could be cached, even temporarily, however,
// far too much of the world is dynamic, and far too many searches
// are looking for dynamic things. the cached results would be useless
// as soon as they are put away -- that's why the limited caches time them out!
final boolean disableCaching= CMProps.getBoolVar(CMProps.Bool.MAPFINDSNOCACHE);
final Vector<Room> rooms=(returnFirst)?null:new Vector<Room>();
final Room curRoom=(mob!=null)?mob.location():null;
boolean searchWeakAreas=false;
boolean searchStrictAreas=false;
boolean searchRooms=false;
boolean searchPlayers=false;
boolean searchItems=false;
boolean searchInhabs=false;
boolean searchInventories=false;
boolean searchStocks=false;
final char[] flags = srchWhatAERIPMVK.toUpperCase().toCharArray();
for (final char flag : flags)
{
switch(flag)
{
case 'E':
searchWeakAreas = true;
break;
case 'A':
searchStrictAreas = true;
break;
case 'R':
searchRooms = true;
break;
case 'P':
searchPlayers = true;
break;
case 'I':
searchItems = true;
break;
case 'M':
searchInhabs = true;
break;
case 'V':
searchInventories = true;
break;
case 'K':
searchStocks = true;
break;
}
}
final long startTime = System.currentTimeMillis();
if(searchRooms)
{
final int dirCode=CMLib.directions().getGoodDirectionCode(cmd);
if((dirCode>=0)&&(curRoom!=null))
room=addWorldRoomsLiberally(rooms,curRoom.rawDoors()[dirCode]);
if(room==null)
room=addWorldRoomsLiberally(rooms,getRoom(cmd));
if((room == null) && (curRoom != null) && (curRoom.getArea()!=null))
room=addWorldRoomsLiberally(rooms,curRoom.getArea().getRoom(cmd));
}
if(room==null)
{
// first get room ids
if((cmd.charAt(0)=='#')&&(curRoom!=null)&&(searchRooms))
{
room=addWorldRoomsLiberally(rooms,getRoom(curRoom.getArea().Name()+cmd));
if(room == null)
room=addWorldRoomsLiberally(rooms,curRoom.getArea().getRoom(curRoom.getArea().Name()+cmd));
}
else
{
final String srchStr=cmd;
if(searchPlayers)
{
// then look for players
final MOB M=CMLib.sessions().findCharacterOnline(srchStr,false);
if(M!=null)
room=addWorldRoomsLiberally(rooms,M.location());
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
// search areas strictly
if(searchStrictAreas && (room==null) && (area==null))
{
area=getArea(srchStr);
if((area!=null) &&(area.properSize()>0) &&(area.getProperRoomnumbers().roomCountAllAreas()>0))
room=addWorldRoomsLiberally(rooms,area);
area=null;
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
final Area A=area;
final MultiEnumeratorBuilder<Room> roomer = new MultiEnumeratorBuilder<Room>()
{
@Override
public MultiEnumeration<Room> getList()
{
if(A==null)
return new MultiEnumeration<Room>(roomsFilled());
else
return new MultiEnumeration<Room>()
.addEnumeration(A.getProperMap())
.addEnumeration(shipsRoomEnumerator(A));
}
};
// no good, so look for room inhabitants
if(searchInhabs && room==null)
{
final Map<String,List<MOB>> finder=getMOBFinder();
List<MOB> candidates=null;
if((mob==null)||(mob.isMonster()))
{
candidates=checkMOBCachedList(finder.get(srchStr.toLowerCase()));
if(returnFirst&&(candidates!=null)&&(candidates.size()>1))
candidates=new XVector<MOB>(candidates.get(0));
}
if(candidates==null)
{
candidates=findInhabitants(roomer.getList(), mob, srchStr,returnFirst, timePct);
if((!disableCaching)&&(!returnFirst)&&((mob==null)||(mob.isMonster())))
finder.put(srchStr.toLowerCase(), candidates);
}
if(candidates.size()>0)
room=addWorldRoomsLiberally(rooms,candidates);
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
// now check room text
if(searchRooms && room==null)
{
final Map<String,List<Room>> finder=getRoomFinder();
List<Room> candidates=null;
if((mob==null)||(mob.isMonster()))
{
candidates=finder.get(srchStr.toLowerCase());
if(returnFirst&&(candidates!=null)&&(candidates.size()>1))
candidates=new XVector<Room>(candidates.get(0));
}
if(candidates==null)
{
candidates=findRooms(roomer.getList(), mob, srchStr, false,returnFirst, timePct);
if((!disableCaching)&&(!returnFirst)&&((mob==null)||(mob.isMonster())))
finder.put(srchStr.toLowerCase(), candidates);
}
if(candidates.size()>0)
room=addWorldRoomsLiberally(rooms,candidates);
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
// check floor items
if(searchItems && room==null)
{
final Map<String,List<Item>> finder=getRoomItemFinder();
List<Item> candidates=null;
if((mob==null)||(mob.isMonster()))
{
candidates=checkRoomItemCachedList(finder.get(srchStr.toLowerCase()));
if(returnFirst&&(candidates!=null)&&(candidates.size()>1))
candidates=new XVector<Item>(candidates.get(0));
}
if(candidates==null)
{
candidates=findRoomItems(roomer.getList(), mob, srchStr, false,returnFirst,timePct);
if((!disableCaching)&&(!returnFirst)&&((mob==null)||(mob.isMonster())))
finder.put(srchStr.toLowerCase(), candidates);
}
if(candidates.size()>0)
room=addWorldRoomsLiberally(rooms,candidates);
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
// check inventories
if(searchInventories && room==null)
{
final Map<String,List<Item>> finder=getInvItemFinder();
List<Item> candidates=null;
if((mob==null)||(mob.isMonster()))
{
candidates=checkInvCachedList(finder.get(srchStr.toLowerCase()));
if(returnFirst&&(candidates!=null)&&(candidates.size()>1))
candidates=new XVector<Item>(candidates.get(0));
}
if(candidates==null)
{
candidates=findInventory(roomer.getList(), mob, srchStr, returnFirst,timePct);
if((!disableCaching)&&(!returnFirst)&&((mob==null)||(mob.isMonster())))
finder.put(srchStr.toLowerCase(), candidates);
}
if(candidates.size()>0)
room=addWorldRoomsLiberally(rooms,candidates);
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
// check stocks
if(searchStocks && room==null)
{
final Map<String,List<Environmental>> finder=getStockFinder();
List<Environmental> candidates=null;
if((mob==null)||(mob.isMonster()))
{
candidates=finder.get(srchStr.toLowerCase());
if(returnFirst&&(candidates!=null)&&(candidates.size()>1))
candidates=new XVector<Environmental>(candidates.get(0));
}
if(candidates==null)
{
candidates=findShopStock(roomer.getList(), mob, srchStr, returnFirst,false,timePct);
if((!disableCaching)&&(!returnFirst)&&((mob==null)||(mob.isMonster())))
finder.put(srchStr.toLowerCase(), candidates);
}
if(candidates.size()>0)
room=addWorldRoomsLiberally(rooms,candidates);
}
if(enforceTimeLimit(startTime,maxMillis))
return returnResponse(rooms,room);
// search areas weakly
if(searchWeakAreas && (room==null) && (A==null))
{
final Area A2=findArea(srchStr);
if((A2!=null) &&(A2.properSize()>0) &&(A2.getProperRoomnumbers().roomCountAllAreas()>0))
room=addWorldRoomsLiberally(rooms,A2);
}
}
}
final List<Room> responseSet = returnResponse(rooms,room);
return responseSet;
}
@Override
public boolean isHere(final CMObject E2, final Room here)
{
if(E2==null)
return false;
else
if(E2==here)
return true;
else
if((E2 instanceof MOB)
&&(((MOB)E2).location()==here))
return true;
else
if((E2 instanceof Item)
&&(((Item)E2).owner()==here))
return true;
else
if((E2 instanceof Item)
&&(((Item)E2).owner()!=null)
&&(((Item)E2).owner() instanceof MOB)
&&(((MOB)((Item)E2).owner()).location()==here))
return true;
else
if(E2 instanceof Exit)
{
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
if(here.getRawExit(d)==E2)
return true;
}
return false;
}
@Override
public boolean isHere(final CMObject E2, final Area here)
{
if(E2==null)
return false;
else
if(E2==here)
return true;
else
if(E2 instanceof Room)
return ((Room)E2).getArea()==here;
else
if(E2 instanceof MOB)
return isHere(((MOB)E2).location(),here);
else
if(E2 instanceof Item)
return isHere(((Item)E2).owner(),here);
return false;
}
protected PairVector<MOB,String> getAllPlayersHere(final Area area, final boolean includeLocalFollowers)
{
final PairVector<MOB,String> playersHere=new PairVector<MOB,String>();
MOB M=null;
Room R=null;
for(final Session S : CMLib.sessions().localOnlineIterable())
{
M=S.mob();
R=(M!=null)?M.location():null;
if((R!=null)&&(R.getArea()==area)&&(M!=null))
{
playersHere.addElement(M,getExtendedRoomID(R));
if(includeLocalFollowers)
{
MOB M2=null;
final Set<MOB> H=M.getGroupMembers(new HashSet<MOB>());
for(final Iterator<MOB> i=H.iterator();i.hasNext();)
{
M2=i.next();
if((M2!=M)&&(M2.location()==R))
playersHere.addElement(M2,getExtendedRoomID(R));
}
}
}
}
return playersHere;
}
@Override
public void resetArea(final Area area)
{
final Area.State oldFlag=area.getAreaState();
area.setAreaState(Area.State.FROZEN);
final PairVector<MOB,String> playersHere=getAllPlayersHere(area,true);
final PairVector<PrivateProperty, String> propertyHere=new PairVector<PrivateProperty, String>();
for(int p=0;p<playersHere.size();p++)
{
final MOB M=playersHere.elementAt(p).first;
final Room R=M.location();
R.delInhabitant(M);
}
for(final Enumeration<Boardable> b=ships();b.hasMoreElements();)
{
final Boardable ship=b.nextElement();
final Room R=roomLocation(ship);
if((R!=null)
&&(R.getArea()==area)
&&(ship instanceof PrivateProperty)
&&(((PrivateProperty)ship).getOwnerName().length()>0)
&&(ship instanceof Item))
{
R.delItem((Item)ship);
propertyHere.add((PrivateProperty)ship,getExtendedRoomID(R));
}
}
for(final Enumeration<Room> r=area.getProperMap();r.hasMoreElements();)
resetRoom(r.nextElement());
area.fillInAreaRooms();
for(int p=0;p<playersHere.size();p++)
{
final MOB M=playersHere.elementAt(p).first;
Room R=getRoom(playersHere.elementAt(p).second);
if(R==null)
R=M.getStartRoom();
if(R==null)
R=getStartRoom(M);
if(R!=null)
R.bringMobHere(M,false);
}
for(int p=0;p<propertyHere.size();p++)
{
final PrivateProperty P=propertyHere.elementAt(p).first;
Room R=getRoom(propertyHere.elementAt(p).second);
if((R==null)||(R.amDestroyed()))
R=getSafeRoomToMovePropertyTo((R==null)?area.getRandomProperRoom():R,P);
if(R!=null)
R.moveItemTo((Item)P);
}
CMLib.database().DBReadAreaData(area);
area.setAreaState(oldFlag);
}
@Override
public boolean hasASky(final Room room)
{
if((room==null)
||(room.domainType()==Room.DOMAIN_OUTDOORS_UNDERWATER)
||((room.domainType()&Room.INDOORS)>0))
return false;
return true;
}
@Override
public void registerWorldObjectDestroyed(Area area, final Room room, final CMObject o)
{
if(o instanceof Deity)
delDeity((Deity)o);
if((o instanceof Boardable)&&(!(o instanceof Area)))
delShip((Boardable)o);
if(o instanceof PostOffice)
CMLib.city().delPostOffice((PostOffice)o);
if(o instanceof Librarian)
CMLib.city().delLibrary((Librarian)o);
if(o instanceof Banker)
CMLib.city().delBank((Banker)o);
if(o instanceof Auctioneer)
CMLib.city().delAuctionHouse((Auctioneer)o);
if(o instanceof PhysicalAgent)
{
final PhysicalAgent AE=(PhysicalAgent)o;
if((area == null) && (room!=null))
area = room.getArea();
if(area == null)
area =getStartArea(AE);
delScriptHost(area, AE);
}
}
@Override
public void registerWorldObjectLoaded(Area area, Room room, final CMObject o)
{
if(o instanceof Deity)
addDeity((Deity)o);
if(o instanceof Boardable)
addShip((Boardable)o);
if(o instanceof PostOffice)
CMLib.city().addPostOffice((PostOffice)o);
if(o instanceof Banker)
CMLib.city().addBank((Banker)o);
if(o instanceof Librarian)
CMLib.city().addLibrary((Librarian)o);
if(o instanceof Auctioneer)
CMLib.city().addAuctionHouse((Auctioneer)o);
if(o instanceof PhysicalAgent)
{
final PhysicalAgent AE=(PhysicalAgent)o;
if(room == null)
room = getStartRoom(AE);
if((area == null) && (room!=null))
area = room.getArea();
if(area == null)
area = getStartArea(AE);
addScriptHost(area, room, AE);
if(o instanceof MOB)
{
for(final Enumeration<Item> i=((MOB)o).items();i.hasMoreElements();)
addScriptHost(area, room, i.nextElement());
}
}
}
protected void cleanScriptHosts(final SLinkedList<LocatedPair> hosts, final PhysicalAgent oneToDel, final boolean fullCleaning)
{
PhysicalAgent PA;
for (final LocatedPair W : hosts)
{
if(W==null)
hosts.remove(W);
else
{
PA=W.obj();
if((PA==null)
||(PA==oneToDel)
||(PA.amDestroyed())
||((fullCleaning)&&(!isAQualifyingScriptHost(PA))))
hosts.remove(W);
}
}
}
protected boolean isAQualifyingScriptHost(final PhysicalAgent host)
{
if(host==null)
return false;
for(final Enumeration<Behavior> e = host.behaviors();e.hasMoreElements();)
{
final Behavior B=e.nextElement();
if((B!=null) && B.isSavable() && (B instanceof ScriptingEngine))
return true;
}
for(final Enumeration<ScriptingEngine> e = host.scripts();e.hasMoreElements();)
{
final ScriptingEngine SE=e.nextElement();
if((SE!=null) && SE.isSavable())
return true;
}
return false;
}
protected boolean isAScriptHost(final Area area, final PhysicalAgent host)
{
if(area == null)
return false;
return isAScriptHost(scriptHostMap.get(area.Name()), host);
}
protected boolean isAScriptHost(final SLinkedList<LocatedPair> hosts, final PhysicalAgent host)
{
if((hosts==null)||(host==null)||(hosts.size()==0))
return false;
for (final LocatedPair W : hosts)
{
if(W.obj()==host)
return true;
}
return false;
}
protected final Object getScriptHostSemaphore(final Area area)
{
final Object semaphore;
if(SCRIPT_HOST_SEMAPHORES.containsKey(area.Name()))
semaphore=SCRIPT_HOST_SEMAPHORES.get(area.Name());
else
{
synchronized(SCRIPT_HOST_SEMAPHORES)
{
semaphore=new Object();
SCRIPT_HOST_SEMAPHORES.put(area.Name(), semaphore);
}
}
return semaphore;
}
protected void addScriptHost(final Area area, final Room room, final PhysicalAgent host)
{
if((area==null) || (host == null))
return;
if(!isAQualifyingScriptHost(host))
return;
synchronized(getScriptHostSemaphore(area))
{
SLinkedList<LocatedPair> hosts = scriptHostMap.get(area.Name());
if(hosts == null)
{
hosts=new SLinkedList<LocatedPair>();
scriptHostMap.put(area.Name(), hosts);
}
else
{
cleanScriptHosts(hosts, null, false);
if(isAScriptHost(hosts,host))
return;
}
hosts.add(new LocatedPairImpl(room, host));
}
}
protected void delScriptHost(Area area, final PhysicalAgent oneToDel)
{
if(oneToDel == null)
return;
if(area == null)
{
for(final Area A : areasList)
{
if(isAScriptHost(A,oneToDel))
{
area = A;
break;
}
}
}
if(area == null)
return;
synchronized(getScriptHostSemaphore(area))
{
final SLinkedList<LocatedPair> hosts = scriptHostMap.get(area.Name());
if(hosts==null)
return;
cleanScriptHosts(hosts, oneToDel, false);
}
}
@Override
@SuppressWarnings("unchecked")
public Enumeration<LocatedPair> scriptHosts(final Area area)
{
final LinkedList<List<LocatedPair>> V = new LinkedList<List<LocatedPair>>();
if(area == null)
{
for(final String areaKey : scriptHostMap.keySet())
V.add(scriptHostMap.get(areaKey));
}
else
{
final SLinkedList<LocatedPair> hosts = scriptHostMap.get(area.Name());
if(hosts==null)
return EmptyEnumeration.INSTANCE;
V.add(hosts);
}
if(V.size()==0)
return EmptyEnumeration.INSTANCE;
final MultiListEnumeration<LocatedPair> me=new MultiListEnumeration<LocatedPair>(V,true);
return new Enumeration<LocatedPair>()
{
@Override
public boolean hasMoreElements()
{
return me.hasMoreElements();
}
@Override
public LocatedPair nextElement()
{
final LocatedPair W = me.nextElement();
final PhysicalAgent E = W.obj();
if(((E==null) || (E.amDestroyed())) && hasMoreElements())
return nextElement();
return W;
}
};
}
@Override
public boolean activate()
{
if(serviceClient==null)
{
name="THMap"+Thread.currentThread().getThreadGroup().getName().charAt(0);
serviceClient=CMLib.threads().startTickDown(this, Tickable.TICKID_SUPPORT|Tickable.TICKID_SOLITARYMASK, MudHost.TIME_SAVETHREAD_SLEEP, 1);
}
return true;
}
@Override
public boolean tick(final Tickable ticking, final int tickID)
{
if((!CMSecurity.isDisabled(CMSecurity.DisFlag.SAVETHREAD))
&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.MAPTHREAD))
&&(tickStatus == Tickable.STATUS_NOT))
{
try
{
tickStatus=Tickable.STATUS_ALIVE;
isDebugging=CMSecurity.isDebugging(DbgFlag.MAPTHREAD);
if(checkDatabase())
roomMaintSweep();
setThreadStatus(serviceClient,"saving props");
Resources.savePropResources();
}
finally
{
tickStatus=Tickable.STATUS_NOT;
setThreadStatus(serviceClient,"sleeping");
}
}
return true;
}
@Override
public boolean shutdown()
{
final boolean debugMem = CMSecurity.isDebugging(CMSecurity.DbgFlag.SHUTDOWN);
for(final Enumeration<Area> a=areasList.elements();a.hasMoreElements();)
{
try
{
final Area A = a.nextElement();
if(A!=null)
{
CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down Map area '"+A.Name()+"'...");
final LinkedList<Room> rooms=new LinkedList<Room>();
for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();)
{
try
{
final Room R=r.nextElement();
if(R!=null)
rooms.add(R);
}
catch(final Exception e)
{
}
}
for(final Iterator<Room> r=rooms.iterator();r.hasNext();)
{
try
{
final Room R=r.next();
A.delProperRoom(R);
R.destroy();
}
catch(final Exception e)
{
}
}
}
if(debugMem)
{
try
{
Object obj = new Object();
final WeakReference<Object> ref = new WeakReference<Object>(obj);
obj = null;
System.gc();
System.runFinalization();
while(ref.get() != null)
{
System.gc();
}
Thread.sleep(3000);
}
catch (final Exception e)
{
}
final long free=Runtime.getRuntime().freeMemory()/1024;
final long total=Runtime.getRuntime().totalMemory()/1024;
if(A!=null)
Log.debugOut("Memory: CMMap: "+A.Name()+": "+(total-free)+"/"+total);
}
}
catch (final Exception e)
{
}
}
areasList.clear();
deitiesList.clear();
shipList.clear();
globalHandlers.clear();
if(CMLib.threads().isTicking(this, TICKID_SUPPORT|Tickable.TICKID_SOLITARYMASK))
{
CMLib.threads().deleteTick(this, TICKID_SUPPORT|Tickable.TICKID_SOLITARYMASK);
serviceClient=null;
}
return true;
}
public void roomMaintSweep()
{
final boolean corpsesOnly=CMSecurity.isSaveFlag(CMSecurity.SaveFlag.ROOMITEMS);
final boolean noMobs=CMSecurity.isSaveFlag(CMSecurity.SaveFlag.ROOMMOBS);
setThreadStatus(serviceClient,"expiration sweep");
final long currentTime=System.currentTimeMillis();
final boolean debug=CMSecurity.isDebugging(CMSecurity.DbgFlag.VACUUM);
final MOB expireM=getFactoryMOB(null);
try
{
final List<Environmental> stuffToGo=new LinkedList<Environmental>();
final List<Room> roomsToGo=new LinkedList<Room>();
final CMMsg expireMsg=CMClass.getMsg(expireM,null,null,CMMsg.MSG_EXPIRE,null);
for(final Enumeration<Room> r=roomsFilled();r.hasMoreElements();)
{
final Room R=r.nextElement();
expireM.setLocation(R);
expireMsg.setTarget(R);
if((R.expirationDate()!=0)
&&(currentTime>R.expirationDate())
&&(R.okMessage(R,expireMsg)))
roomsToGo.add(R);
else
if(!R.amDestroyed())
{
stuffToGo.clear();
for(int i=0;i<R.numItems();i++)
{
final Item I=R.getItem(i);
if((I!=null)
&&((!corpsesOnly)||(I instanceof DeadBody))
&&(I.expirationDate()!=0)
&&(I.owner()==R)
&&(currentTime>I.expirationDate()))
stuffToGo.add(I);
}
if(!noMobs)
{
for(int i=0;i<R.numInhabitants();i++)
{
final MOB M=R.fetchInhabitant(i);
if((M!=null)
&&(M.expirationDate()!=0)
&&(currentTime>M.expirationDate()))
stuffToGo.add(M);
}
}
}
if(stuffToGo.size()>0)
{
boolean success=true;
for(final Environmental E : stuffToGo)
{
setThreadStatus(serviceClient,"expiring "+E.Name());
expireMsg.setTarget(E);
if(R.okMessage(expireM,expireMsg))
R.sendOthers(expireM,expireMsg);
else
success=false;
if(debug)
Log.sysOut("UTILITHREAD","Expired "+E.Name()+" in "+getExtendedRoomID(R)+": "+success);
}
stuffToGo.clear();
}
}
for(final Room R : roomsToGo)
{
expireM.setLocation(R);
expireMsg.setTarget(R);
setThreadStatus(serviceClient,"expirating room "+getExtendedRoomID(R));
if(debug)
{
String roomID=getExtendedRoomID(R);
if(roomID.length()==0)
roomID="(unassigned grid room, probably in the air)";
if(debug)
Log.sysOut("UTILITHREAD","Expired "+roomID+".");
}
R.sendOthers(expireM,expireMsg);
}
}
catch(final java.util.NoSuchElementException e)
{
}
setThreadStatus(serviceClient,"title sweeping");
final LegalLibrary law=CMLib.law();
final Set<String> playerList=new TreeSet<String>();
try
{
final Set<LandTitle> titlesDone = new HashSet<LandTitle>();
for(final Enumeration<Area> a=areas();a.hasMoreElements();)
{
final Area A=a.nextElement();
if(A.numEffects()>0)
{
final LandTitle T=law.getLandTitle(A);
if((T!=null)
&&(!titlesDone.contains(T)))
{
T.updateLot(playerList);
titlesDone.add(T);
}
}
}
for(final Enumeration<Room> r=rooms();r.hasMoreElements();)
{
final Room R=r.nextElement();
// roomid > 0? these are unfilled...
if(R.numEffects()>0)
{
for(final Enumeration<Ability> a=R.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if(A instanceof LandTitle)
{
final LandTitle T=(LandTitle)A;
if(!titlesDone.contains(T))
{
T.updateLot(playerList);
titlesDone.add(T);
}
}
}
}
}
}
catch(final NoSuchElementException nse)
{
}
setThreadStatus(serviceClient,"cleaning scripts");
for(final String areaKey : scriptHostMap.keySet())
cleanScriptHosts(scriptHostMap.get(areaKey), null, true);
final long lastDateTime=System.currentTimeMillis()-(5*TimeManager.MILI_MINUTE);
setThreadStatus(serviceClient,"checking");
try
{
for(final Enumeration<Room> r=roomsFilled();r.hasMoreElements();)
{
final Room R=r.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
final MOB mob=R.fetchInhabitant(m);
if(mob == null)
continue;
if(mob.amDestroyed())
{
R.delInhabitant(mob);
continue;
}
if((mob.lastTickedDateTime()>0)
&&(mob.lastTickedDateTime()<lastDateTime))
{
final boolean ticked=CMLib.threads().isTicking(mob,Tickable.TICKID_MOB);
final boolean isDead=mob.amDead();
final Room startR=mob.getStartRoom();
final String wasFrom=(startR!=null)?startR.roomID():"NULL";
if(!ticked)
{
if(!mob.isPlayer())
{
if(ticked)
{
// we have a dead group.. let the group handler deal with it.
Log.errOut(serviceClient.getName(),mob.name()+" in room "+getDescriptiveExtendedRoomID(R)
+" unticked in dead group (Home="+wasFrom+") since: "+CMLib.time().date2String(mob.lastTickedDateTime())+".");
continue;
}
else
{
Log.errOut(serviceClient.getName(),mob.name()+" in room "+getDescriptiveExtendedRoomID(R)
+" unticked (is ticking="+(ticked)+", dead="+isDead+", Home="+wasFrom+") since: "+CMLib.time().date2String(mob.lastTickedDateTime())+"."+(ticked?"":" This mob has been destroyed. May he rest in peace."));
mob.destroy();
}
}
else
{
Log.errOut(serviceClient.getName(),"Player "+mob.name()+" in room "+getDescriptiveExtendedRoomID(R)
+" unticked (is ticking="+(ticked)+", dead="+isDead+", Home="+wasFrom+") since: "+CMLib.time().date2String(mob.lastTickedDateTime())+"."+(ticked?"":" This mob has been put aside."));
}
R.delInhabitant(mob);//keeps it from happening again.
setThreadStatus(serviceClient,"checking");
}
}
}
}
}
catch(final java.util.NoSuchElementException e)
{
}
finally
{
if(expireM!=null)
expireM.destroy();
}
}
protected final static char[] cmfsFilenameifyChars=new char[]{'/','\\',' '};
protected String cmfsFilenameify(final String str)
{
return CMStrings.replaceAllofAny(str, cmfsFilenameifyChars, '_').toLowerCase().trim();
}
// this is a beautiful idea, but im scared of the memory of all the final refs
protected void addMapStatFiles(final List<CMFile.CMVFSFile> rootFiles, final Room R, final Environmental E, final CMFile.CMVFSDir root)
{
rootFiles.add(new CMFile.CMVFSDir(root,root.getPath()+"stats/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
final String[] stats=E.getStatCodes();
final String oldName=E.Name();
for (final String statName : stats)
{
final String statValue=E.getStat(statName);
myFiles.add(new CMFile.CMVFSFile(this.getPath()+statName,256,System.currentTimeMillis(),"SYS")
{
@Override
public int getMaskBits(final MOB accessor)
{
if(accessor==null)
return this.mask;
if((E instanceof Area)&&(CMSecurity.isAllowed(accessor,((Area)E).getRandomProperRoom(),CMSecurity.SecFlag.CMDAREAS)))
return this.mask;
else
if(CMSecurity.isAllowed(accessor,R,CMSecurity.SecFlag.CMDROOMS))
return this.mask;
else
if((E instanceof MOB) && CMSecurity.isAllowed(accessor,R,CMSecurity.SecFlag.CMDMOBS))
return this.mask;
else
if((E instanceof Item) && CMSecurity.isAllowed(accessor,R,CMSecurity.SecFlag.CMDITEMS))
return this.mask;
return this.mask|48;
}
@Override
public Object readData()
{
return statValue;
}
@Override
public void saveData(final String filename, final int vfsBits, final String author, final Object O)
{
E.setStat(statName, O.toString());
if(E instanceof Area)
CMLib.database().DBUpdateArea(oldName, (Area)E);
else
if(E instanceof Room)
CMLib.database().DBUpdateRoom((Room)E);
else
if(E instanceof MOB)
CMLib.database().DBUpdateMOB(R.roomID(), (MOB)E);
else
if(E instanceof Item)
CMLib.database().DBUpdateItem(R.roomID(), (Item)E);
}
});
}
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
});
}
@Override
public CMFile.CMVFSDir getMapRoot(final CMFile.CMVFSDir root)
{
return new CMFile.CMVFSDir(root,root.getPath()+"map/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>(numAreas());
for(final Enumeration<Area> a=areas();a.hasMoreElements();)
{
final Area A=a.nextElement();
myFiles.add(new CMFile.CMVFSFile(this.getPath()+cmfsFilenameify(A.Name())+".cmare",48,System.currentTimeMillis(),"SYS")
{
@Override
public Object readData()
{
return CMLib.coffeeMaker().getAreaXML(A, null, null, null, true);
}
});
myFiles.add(new CMFile.CMVFSDir(this,this.getPath()+cmfsFilenameify(A.Name())+"/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
for(final Enumeration<Room> r=A.getFilledProperMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
if(R.roomID().length()>0)
{
String roomID=R.roomID();
if(roomID.startsWith(A.Name()+"#"))
roomID=roomID.substring(A.Name().length()+1);
myFiles.add(new CMFile.CMVFSFile(this.getPath()+cmfsFilenameify(R.roomID())+".cmare",48,System.currentTimeMillis(),"SYS")
{
@Override
public Object readData()
{
return CMLib.coffeeMaker().getRoomXML(R, null, null, true);
}
});
myFiles.add(new CMFile.CMVFSDir(this,this.getPath()+cmfsFilenameify(roomID).toLowerCase()+"/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
myFiles.add(new CMFile.CMVFSFile(this.getPath()+"items.cmare",48,System.currentTimeMillis(),"SYS")
{
@Override
public Object readData()
{
return CMLib.coffeeMaker().getRoomItems(R, new TreeMap<String,List<Item>>(), null, null);
}
});
myFiles.add(new CMFile.CMVFSFile(this.path+"mobs.cmare",48,System.currentTimeMillis(),"SYS")
{
@Override
public Object readData()
{
return CMLib.coffeeMaker().getRoomMobs(R, null, null, new TreeMap<String,List<MOB>>());
}
});
myFiles.add(new CMFile.CMVFSDir(this,this.path+"mobs/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
final Room R2=CMLib.coffeeMaker().makeNewRoomContent(R, false);
if(R2!=null)
{
for(int i=0;i<R2.numInhabitants();i++)
{
final MOB M=R2.fetchInhabitant(i);
myFiles.add(new CMFile.CMVFSFile(this.path+cmfsFilenameify(R2.getContextName(M))+".cmare",48,System.currentTimeMillis(),"SYS")
{
@Override
public Object readData()
{
return CMLib.coffeeMaker().getMobXML(M);
}
});
myFiles.add(new CMFile.CMVFSDir(this,this.path+cmfsFilenameify(R2.getContextName(M))+"/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
addMapStatFiles(myFiles,R,M,this);
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
});
}
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
}
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
});
myFiles.add(new CMFile.CMVFSDir(this,this.path+"items/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
final Room R2=CMLib.coffeeMaker().makeNewRoomContent(R, false);
if(R2 != null)
{
for(int i=0;i<R2.numItems();i++)
{
final Item I=R2.getItem(i);
myFiles.add(new CMFile.CMVFSFile(this.path+cmfsFilenameify(R2.getContextName(I))+".cmare",48,System.currentTimeMillis(),"SYS")
{
@Override
public Object readData()
{
return CMLib.coffeeMaker().getItemXML(I);
}
});
myFiles.add(new CMFile.CMVFSDir(this,this.path+cmfsFilenameify(R2.getContextName(I))+"/")
{
@Override
protected CMFile.CMVFSFile[] getFiles()
{
final List<CMFile.CMVFSFile> myFiles=new Vector<CMFile.CMVFSFile>();
addMapStatFiles(myFiles,R,I,this);
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
});
}
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
return new CMFile.CMVFSFile[0];
}
});
addMapStatFiles(myFiles,R,R,this);
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
});
}
}
addMapStatFiles(myFiles,null,A,this);
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
});
}
Collections.sort(myFiles,CMFile.CMVFSDir.fcomparator);
return myFiles.toArray(new CMFile.CMVFSFile[0]);
}
};
}
}
|
git-svn-id: svn://192.168.1.10/public/CoffeeMud@21700 0d6f1817-ed0e-0410-87c9-987e46238f29
| com/planet_ink/coffee_mud/Libraries/CMMap.java | <ide><path>om/planet_ink/coffee_mud/Libraries/CMMap.java
<ide> boolean success=true;
<ide> for(final Environmental E : stuffToGo)
<ide> {
<del> setThreadStatus(serviceClient,"expiring "+E.Name());
<add> //setThreadStatus(serviceClient,"expiring "+E.Name()); // just too much -- ms count here
<ide> expireMsg.setTarget(E);
<ide> if(R.okMessage(expireM,expireMsg))
<ide> R.sendOthers(expireM,expireMsg);
<ide> +" unticked (is ticking="+(ticked)+", dead="+isDead+", Home="+wasFrom+") since: "+CMLib.time().date2String(mob.lastTickedDateTime())+"."+(ticked?"":" This mob has been put aside."));
<ide> }
<ide> R.delInhabitant(mob);//keeps it from happening again.
<del> setThreadStatus(serviceClient,"checking");
<ide> }
<ide> }
<ide> } |
||
JavaScript | mit | c6e670940d21f6944dcc7336f5e0409523889792 | 0 | projectweekend/Pi-Sensor-RPC-Service | var os = require( "os" );
var async = require( "async" );
var throng = require( "throng" );
var connections = require( "./shared/connections" );
var utils = require( "./shared/utils" );
var logger = connections.logger( [ "Pi-Sensor-RPC-Service" ] );
var run = function () {
logger.log( "Starting Pi-Sensor-RPC-Service" );
var serialPort = connections.serialport();
var broker = connections.jackrabbit();
var serialResponse = null;
var serialWrite = function ( data ) {
return function ( done ) {
serialResponse = null;
serialPort.write( data, done );
};
};
var serialDrain = function ( done ) {
serialPort.drain( done );
};
var getSerialResponse = function ( done ) {
var takingTooLong = false;
var start = new Date();
while ( !serialResponse && !takingTooLong ) {
var end = new Date();
takingTooLong = end - start > 2000;
}
if ( serialResponse ) {
return done( null, serialResponse );
}
return done( new Error( "Serial response timeout" ) );
};
var handleMessage = function ( message, ack ) {
console.log( "Calling message handler" );
async.series( [
serialWrite( message.serialMessage ),
serialDrain,
getSerialResponse
], function ( err, result ) {
if ( err ) {
console.log( err );
logger.log( err );
ack();
process.exit( 1 );
}
return ack( result[ 2 ] );
} );
};
var serve = function () {
console.log( "Serve" );
broker.handle( "sensor.get", handleMessage );
};
var create = function () {
console.log( "Create" );
broker.create( "sensor.get", { prefetch: 5 }, serve );
};
process.once( "uncaughtException", function ( err ) {
logger.log( "Stopping Pi-Sensor-RPC-Service" );
logger.log( err );
process.exit();
} );
serialPort.on( "open", function () {
console.log( "Serial Open" );
serialPort.on( "data", function ( data ) {
console.log( "Serial data handler registered" );
serialData = utils.parseSerialData( data );
} );
logger.log( "Serial port open" );
broker.once( "connected", create );
} );
};
throng( run, {
workers: os.cpus().length,
lifetime: Infinity
} );
| app/main.js | var os = require( "os" );
var async = require( "async" );
var throng = require( "throng" );
var connections = require( "./shared/connections" );
var utils = require( "./shared/utils" );
var logger = connections.logger( [ "Pi-Sensor-RPC-Service" ] );
var run = function () {
logger.log( "Starting Pi-Sensor-RPC-Service" );
var serialPort = connections.serialport();
var broker = connections.jackrabbit();
var serialResponse = null;
var serialWrite = function ( data ) {
return function ( done ) {
serialResponse = null;
serialPort.write( data, done );
};
};
var serialDrain = function ( done ) {
serialPort.drain( done );
};
var getSerialResponse = function ( done ) {
var takingTooLong = false;
var start = new Date();
while ( !serialResponse && !takingTooLong ) {
var end = new Date();
takingTooLong = end - start > 500;
}
if ( serialResponse ) {
return done( null, serialResponse );
}
return done( new Error( "Serial response timeout" ) );
};
var handleMessage = function ( message, ack ) {
console.log( "Calling message handler" );
async.series( [
serialWrite( message.serialMessage ),
serialDrain,
getSerialResponse
], function ( err, result ) {
if ( err ) {
console.log( err );
logger.log( err );
ack();
process.exit( 1 );
}
return ack( result[ 2 ] );
} );
};
var serve = function () {
console.log( "Serve" );
broker.handle( "sensor.get", handleMessage );
};
var create = function () {
console.log( "Create" );
broker.create( "sensor.get", { prefetch: 5 }, serve );
};
process.once( "uncaughtException", function ( err ) {
logger.log( "Stopping Pi-Sensor-RPC-Service" );
logger.log( err );
process.exit();
} );
serialPort.on( "open", function () {
console.log( "Serial Open" );
serialPort.on( "data", function ( data ) {
console.log( "Serial data handler registered" );
serialData = utils.parseSerialData( data );
} );
logger.log( "Serial port open" );
broker.once( "connected", create );
} );
};
throng( run, {
workers: os.cpus().length,
lifetime: Infinity
} );
| Change
| app/main.js | Change | <ide><path>pp/main.js
<ide> var start = new Date();
<ide> while ( !serialResponse && !takingTooLong ) {
<ide> var end = new Date();
<del> takingTooLong = end - start > 500;
<add> takingTooLong = end - start > 2000;
<ide> }
<ide>
<ide> if ( serialResponse ) { |
|
Java | apache-2.0 | fd2f40767a4b8fafa7399dab119d2232632284b9 | 0 | ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma | /*
* The Gemma project
*
* Copyright (c) 2012 University of British Columbia
*
* 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 ubic.gemma.loader.expression.geo;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ubic.basecode.dataStructure.matrix.DenseDoubleMatrix;
import ubic.basecode.dataStructure.matrix.DoubleMatrix;
import ubic.basecode.io.ByteArrayConverter;
import ubic.basecode.math.DescriptiveWithMissing;
import ubic.gemma.analysis.expression.AnalysisUtilService;
import ubic.gemma.analysis.preprocess.ProcessedExpressionDataVectorCreateService;
import ubic.gemma.analysis.preprocess.SampleCoexpressionMatrixService;
import ubic.gemma.analysis.preprocess.svd.SVDService;
import ubic.gemma.datastructure.matrix.ExpressionDataDoubleMatrix;
import ubic.gemma.expression.experiment.service.ExpressionExperimentService;
import ubic.gemma.loader.expression.AffyPowerToolsProbesetSummarize;
import ubic.gemma.loader.expression.geo.fetcher.RawDataFetcher;
import ubic.gemma.loader.expression.geo.service.GeoService;
import ubic.gemma.model.common.auditAndSecurity.AuditTrailService;
import ubic.gemma.model.common.auditAndSecurity.eventType.AuditEventType;
import ubic.gemma.model.common.auditAndSecurity.eventType.DataAddedEvent;
import ubic.gemma.model.common.auditAndSecurity.eventType.DataReplacedEvent;
import ubic.gemma.model.common.auditAndSecurity.eventType.ExpressionExperimentPlatformSwitchEvent;
import ubic.gemma.model.common.description.LocalFile;
import ubic.gemma.model.common.description.VocabCharacteristic;
import ubic.gemma.model.common.quantitationtype.GeneralType;
import ubic.gemma.model.common.quantitationtype.PrimitiveType;
import ubic.gemma.model.common.quantitationtype.QuantitationType;
import ubic.gemma.model.common.quantitationtype.ScaleType;
import ubic.gemma.model.common.quantitationtype.StandardQuantitationType;
import ubic.gemma.model.expression.arrayDesign.ArrayDesign;
import ubic.gemma.model.expression.arrayDesign.ArrayDesignService;
import ubic.gemma.model.expression.bioAssay.BioAssay;
import ubic.gemma.model.expression.bioAssay.BioAssayService;
import ubic.gemma.model.expression.bioAssayData.BioAssayDimension;
import ubic.gemma.model.expression.bioAssayData.BioAssayDimensionService;
import ubic.gemma.model.expression.bioAssayData.RawExpressionDataVector;
import ubic.gemma.model.expression.biomaterial.BioMaterial;
import ubic.gemma.model.expression.biomaterial.BioMaterialService;
import ubic.gemma.model.expression.designElement.CompositeSequence;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.genome.Taxon;
import cern.colt.list.DoubleArrayList;
/**
* Update the data associated with an experiment. Primary designed for filling in data that we can't or don't want to
* get from GEO. For loading experiments from flat files, see SimpleExpressionDataLoaderService
*
* @author paul
* @version $Id$
*/
@Component
public class DataUpdater {
private static Log log = LogFactory.getLog( DataUpdater.class );
@Autowired
private ArrayDesignService arrayDesignService;
@Autowired
private BioAssayDimensionService assayDimensionService;
@Autowired
private BioMaterialService bioMaterialService;
@Autowired
private BioAssayService bioAssayService;
@Autowired
private AuditTrailService auditTrailService;
@Autowired
private ExpressionExperimentService experimentService;
@Autowired
private AnalysisUtilService analysisUtilService;
@Autowired
private GeoService geoService;
@Autowired
private ProcessedExpressionDataVectorCreateService processedExpressionDataVectorCreateService;
@Autowired
private SampleCoexpressionMatrixService sampleCoexpressionMatrixService;
@Autowired
private SVDService svdService;
public ExpressionExperiment addAffyExonArrayData( ExpressionExperiment ee ) {
Collection<ArrayDesign> ads = experimentService.getArrayDesignsUsed( ee );
if ( ads.size() > 1 ) {
throw new IllegalArgumentException( "Can't handle experiments with more than one platform" );
}
return addAffyExonArrayData( ee, ads.iterator().next() );
}
/**
* Replaces any existing "preferred" dat.
*
* @param ee
* @param ad
*/
public ExpressionExperiment addAffyExonArrayData( ExpressionExperiment ee, ArrayDesign ad ) {
RawDataFetcher f = new RawDataFetcher();
Collection<LocalFile> files = f.fetch( ee.getAccession().getAccession() );
if ( files.isEmpty() ) {
throw new RuntimeException( "Data was apparently not available" );
}
ad = arrayDesignService.thaw( ad );
ee = experimentService.thawLite( ee );
Taxon primaryTaxon = ad.getPrimaryTaxon();
ArrayDesign targetPlatform = prepareTargetPlatformForExonArrays( primaryTaxon );
assert !targetPlatform.getCompositeSequences().isEmpty();
AffyPowerToolsProbesetSummarize apt = new AffyPowerToolsProbesetSummarize();
Collection<RawExpressionDataVector> vectors = apt.processExonArrayData( ee, targetPlatform, files );
if ( vectors.isEmpty() ) {
throw new IllegalStateException( "No vectors were returned for " + ee );
}
ee = experimentService.replaceVectors( ee, targetPlatform, vectors );
if ( !targetPlatform.equals( ad ) ) {
AuditEventType eventType = ExpressionExperimentPlatformSwitchEvent.Factory.newInstance();
auditTrailService.addUpdateEvent( ee, eventType,
"Switched in course of updating vectors using AffyPowerTools (from " + ad.getShortName() + " to "
+ targetPlatform.getShortName() + ")" );
}
audit( ee, "Data vector computation from CEL files using AffyPowerTools for " + targetPlatform, true );
postprocess( ee );
return ee;
}
/**
* Use when we want to avoid downloading the CEL files etc. For example if GEO doesn't have them and we ran
* apt-probeset-summarize ourselves.
*
* @param ee
* @param pathToAptOutputFile
* @throws IOException
* @throws FileNotFoundException
*/
public void addAffyExonArrayData( ExpressionExperiment ee, String pathToAptOutputFile )
throws FileNotFoundException, IOException {
Collection<ArrayDesign> ads = experimentService.getArrayDesignsUsed( ee );
if ( ads.size() > 1 ) {
throw new IllegalArgumentException( "Can't handle experiments with more than one platform" );
}
ArrayDesign ad = ads.iterator().next();
ad = arrayDesignService.thaw( ad );
ee = experimentService.thawLite( ee );
Taxon primaryTaxon = ad.getPrimaryTaxon();
ArrayDesign targetPlatform = prepareTargetPlatformForExonArrays( primaryTaxon );
AffyPowerToolsProbesetSummarize apt = new AffyPowerToolsProbesetSummarize();
Collection<RawExpressionDataVector> vectors = apt
.processExonArrayData( ee, pathToAptOutputFile, targetPlatform );
if ( vectors.isEmpty() ) {
throw new IllegalStateException( "No vectors were returned for " + ee );
}
experimentService.replaceVectors( ee, targetPlatform, vectors );
if ( !targetPlatform.equals( ad ) ) {
AuditEventType eventType = ExpressionExperimentPlatformSwitchEvent.Factory.newInstance();
auditTrailService.addUpdateEvent( ee, eventType,
"Switched in course of updating vectors using AffyPowerTools (from " + ad.getShortName() + " to "
+ targetPlatform.getShortName() + ")" );
}
audit( ee, "Data vector input from APT output file " + pathToAptOutputFile + " on " + targetPlatform, true );
postprocess( ee );
}
/**
* Add an additional data (with associated quantitation type) to the selected experiment. Will do postprocessing if
* the data quantitationtype is 'preferred', but if there is already a preferred quantitation type, an error will be
* thrown.
*
* @param ee
* @param targetPlatform
* @param data
*/
public ExpressionExperiment addData( ExpressionExperiment ee, ArrayDesign targetPlatform,
ExpressionDataDoubleMatrix data ) {
Collection<ArrayDesign> ads = experimentService.getArrayDesignsUsed( ee );
if ( ads.size() > 1 ) {
throw new IllegalArgumentException( "Can only replace data for an experiment that uses one platform; "
+ "you must switch/merge first and then provide appropriate replacement data." );
}
if ( data.rows() == 0 ) {
throw new IllegalArgumentException( "Data had no rows" );
}
ArrayDesign originalArrayDesign = ads.iterator().next();
if ( !targetPlatform.equals( originalArrayDesign ) ) {
throw new IllegalArgumentException(
"You can only add data for a platform that already is used for the experiment: "
+ originalArrayDesign + " != targeted " + targetPlatform );
}
Collection<QuantitationType> qts = data.getQuantitationTypes();
if ( qts.size() > 1 ) {
throw new IllegalArgumentException( "Only support a single quantitation type" );
}
if ( qts.isEmpty() ) {
throw new IllegalArgumentException( "Please supply a quantitation type with the data" );
}
QuantitationType qt = qts.iterator().next();
if ( qt.getIsPreferred() ) {
for ( QuantitationType existingQt : ee.getQuantitationTypes() ) {
if ( existingQt.getIsPreferred() ) {
throw new IllegalArgumentException(
"You cannot add 'preferred' data to an experiment that already has it. You should first make the existing data non-preferred." );
}
}
}
Collection<RawExpressionDataVector> vectors = makeNewVectors( ee, targetPlatform, data, qt );
if ( vectors.isEmpty() ) {
throw new IllegalStateException( "no vectors!" );
}
ee = experimentService.addVectors( ee, originalArrayDesign, vectors );
audit( ee, "Data vectors added for " + targetPlatform + ", " + qt, false );
if ( qt.getIsPreferred() ) {
postprocess( ee );
}
// debug code.
for ( BioAssay ba : ee.getBioAssays() ) {
assert ba.getArrayDesignUsed().equals( targetPlatform );
}
experimentService.update( ee );
return ee;
}
/**
* @param ee
* @param qt
* @return
*/
public int deleteData( ExpressionExperiment ee, QuantitationType qt ) {
return this.experimentService.removeData( ee, qt );
}
/**
* @param ee
*/
public void postprocess( ExpressionExperiment ee ) {
processedExpressionDataVectorCreateService.computeProcessedExpressionData( ee );
sampleCoexpressionMatrixService.delete( ee );
sampleCoexpressionMatrixService.create( ee, true );
svdService.svd( ee.getId() );
}
/**
* Replace the data associated with the experiment (or add it if there is none). These data become the 'preferred'
* quantitation type.
* <p>
* Similar to AffyPowerToolsProbesetSummarize.convertDesignElementDataVectors and code in
* SimpleExpressionDataLoaderService.
*
* @param ee the experiment to be modified
* @param targetPlatform the platform for the new data
* @param data the data to be used
*/
public ExpressionExperiment replaceData( ExpressionExperiment ee, ArrayDesign targetPlatform,
ExpressionDataDoubleMatrix data ) {
Collection<ArrayDesign> ads = experimentService.getArrayDesignsUsed( ee );
if ( ads.size() > 1 ) {
throw new IllegalArgumentException( "Can only replace data for an experiment that uses one platform; "
+ "you must switch/merge first and then provide appropriate replacement data." );
}
if ( data.rows() == 0 ) {
throw new IllegalArgumentException( "Data had no rows" );
}
ArrayDesign originalArrayDesign = ads.iterator().next();
Collection<QuantitationType> qts = data.getQuantitationTypes();
if ( qts.size() > 1 ) {
throw new IllegalArgumentException( "Only support a single quantitation type" );
}
if ( qts.isEmpty() ) {
throw new IllegalArgumentException( "Please supply a quantitation type with the data" );
}
QuantitationType qt = qts.iterator().next();
qt.setIsPreferred( true );
Collection<RawExpressionDataVector> vectors = makeNewVectors( ee, targetPlatform, data, qt );
if ( vectors.isEmpty() ) {
throw new IllegalStateException( "no vectors!" );
}
/*
* delete all analyses, etc.
*/
analysisUtilService.deleteOldAnalyses( ee );
ee = experimentService.replaceVectors( ee, targetPlatform, vectors );
// audit if we switched platforms.
if ( !targetPlatform.equals( originalArrayDesign ) ) {
AuditEventType eventType = ExpressionExperimentPlatformSwitchEvent.Factory.newInstance();
auditTrailService.addUpdateEvent(
ee,
eventType,
"Switched in course of updating vectors using data input (from "
+ originalArrayDesign.getShortName() + " to " + targetPlatform.getShortName() + ")" );
}
audit( ee, "Data vector replacement for " + targetPlatform, true );
postprocess( ee );
// debug code.
for ( BioAssay ba : ee.getBioAssays() ) {
assert ba.getArrayDesignUsed().equals( targetPlatform );
}
experimentService.update( ee );
return ee;
}
/**
* Replaces data.
*
* @param ee
* @param targetArrayDesign
* @param countMatrix Representing 'raw' counts (added after rpkm, if provided), which is treated as the 'preferred'
* data. If this is provided, all the other data will be removed.
* @param rpkmMatrix Representing per-gene normalized data, optional.
*/
public void addCountDataMatricesToExperiment( ExpressionExperiment ee, ArrayDesign targetArrayDesign,
DoubleMatrix<String, String> countMatrix, DoubleMatrix<String, String> rpkmMatrix ) {
// make the proper matrices we need for loading.
if ( countMatrix == null )
throw new IllegalArgumentException( "You must provide count matrix (rpkm is optional)" );
targetArrayDesign = arrayDesignService.thaw( targetArrayDesign );
/*
* Treat this as the preferred data, so we have to do it first.
*/
DoubleMatrix<CompositeSequence, BioMaterial> properCountMatrix = matchElementsToRowNames( targetArrayDesign,
countMatrix );
matchBioMaterialsToColNames( ee, countMatrix, properCountMatrix );
QuantitationType countqt = makeQt( true );
countqt.setName( "Counts" );
countqt.setDescription( "Read counts" );
countqt.setIsBackgroundSubtracted( false );
countqt.setIsNormalized( false );
ExpressionDataDoubleMatrix countEEMatrix = new ExpressionDataDoubleMatrix( ee, countqt, properCountMatrix );
ee = replaceData( ee, targetArrayDesign, countEEMatrix );
addTotalCountInformation( ee, countEEMatrix );
if ( rpkmMatrix != null ) {
DoubleMatrix<CompositeSequence, BioMaterial> properRPKMMatrix = matchElementsToRowNames( targetArrayDesign,
rpkmMatrix );
matchBioMaterialsToColNames( ee, rpkmMatrix, properRPKMMatrix );
QuantitationType rpkmqt = makeQt( false );
rpkmqt.setIsRatio( false );
rpkmqt.setName( "RPKM" );
rpkmqt.setDescription( "Reads (or fragments) per kb of gene model per million reads" );
rpkmqt.setIsBackgroundSubtracted( false );
rpkmqt.setIsNormalized( true );
ExpressionDataDoubleMatrix rpkmEEMatrix = new ExpressionDataDoubleMatrix( ee, rpkmqt, properRPKMMatrix );
ee = addData( ee, targetArrayDesign, rpkmEEMatrix );
}
}
/**
* @param ee
* @param countEEMatrix
*/
private void addTotalCountInformation( ExpressionExperiment ee, ExpressionDataDoubleMatrix countEEMatrix ) {
for ( BioAssay ba : ee.getBioAssays() ) {
Double[] col = countEEMatrix.getColumn( ba );
double librarySize = DescriptiveWithMissing.sum( new DoubleArrayList( ArrayUtils.toPrimitive( col ) ) );
// Ideally also know read length.
ba.setDescription( ba.getDescription() + " totalCounts=" + Math.floor( librarySize ) );
// This isn't a very good place to keep this...
VocabCharacteristic countTerm = VocabCharacteristic.Factory.newInstance();
countTerm.setName( "LibrarySize" );
countTerm.setDescription( "Total read counts in sample, computed from the imported data." );
// this is really a placeholder.
countTerm.setCategory( "count" );
countTerm.setCategoryUri( "http://purl.obolibrary.org/obo/PATO_0000070" );
countTerm.setValue( String.format( "%d", ( int ) Math.floor( librarySize ) ) );
BioMaterial bm = ba.getSamplesUsed().iterator().next();
bm.getCharacteristics().add( countTerm );
bioMaterialService.update( bm );
bioAssayService.update( ba );
}
}
/**
* @param ee
* @param note
* @param replace if true, use a DataReplacedEvent; otherwise DataAddedEvent.
*/
private void audit( ExpressionExperiment ee, String note, boolean replace ) {
AuditEventType eventType = null;
if ( replace ) {
eventType = DataReplacedEvent.Factory.newInstance();
} else {
eventType = DataAddedEvent.Factory.newInstance();
}
auditTrailService.addUpdateEvent( ee, eventType, note );
}
/**
* @param ee
* @param targetPlatform
* @param data
* @param qt
* @return
*/
private Collection<RawExpressionDataVector> makeNewVectors( ExpressionExperiment ee, ArrayDesign targetPlatform,
ExpressionDataDoubleMatrix data, QuantitationType qt ) {
ByteArrayConverter bArrayConverter = new ByteArrayConverter();
Collection<RawExpressionDataVector> vectors = new HashSet<RawExpressionDataVector>();
BioAssayDimension bioAssayDimension = data.getBestBioAssayDimension();
assert bioAssayDimension != null;
assert !bioAssayDimension.getBioAssays().isEmpty();
bioAssayDimension = assayDimensionService.findOrCreate( bioAssayDimension );
assert !bioAssayDimension.getBioAssays().isEmpty();
for ( int i = 0; i < data.rows(); i++ ) {
byte[] bdata = bArrayConverter.doubleArrayToBytes( data.getRow( i ) );
RawExpressionDataVector vector = RawExpressionDataVector.Factory.newInstance();
vector.setData( bdata );
CompositeSequence cs = data.getRowElement( i ).getDesignElement();
if ( cs == null ) {
continue;
}
if ( !cs.getArrayDesign().equals( targetPlatform ) ) {
throw new IllegalArgumentException( "Input data must use the target platform (was: "
+ cs.getArrayDesign() + ", expected: " + targetPlatform );
}
vector.setDesignElement( cs );
vector.setQuantitationType( qt );
vector.setExpressionExperiment( ee );
vector.setBioAssayDimension( bioAssayDimension );
vectors.add( vector );
}
return vectors;
}
/**
* @param preferred
* @return
*/
private QuantitationType makeQt( boolean preferred ) {
QuantitationType qt = QuantitationType.Factory.newInstance();
qt.setGeneralType( GeneralType.QUANTITATIVE );
qt.setScale( ScaleType.LINEAR );
qt.setIsBackground( false );
qt.setIsRatio( false );
qt.setIsBackgroundSubtracted( true );
qt.setIsNormalized( true );
qt.setIsMaskedPreferred( true );
qt.setIsPreferred( preferred );
qt.setIsBatchCorrected( false );
qt.setType( StandardQuantitationType.AMOUNT );
qt.setRepresentation( PrimitiveType.DOUBLE );
return qt;
}
/**
* @param ee
* @param rawMatrix
* @param finalMatrix
*/
private void matchBioMaterialsToColNames( ExpressionExperiment ee, DoubleMatrix<String, String> rawMatrix,
DoubleMatrix<CompositeSequence, BioMaterial> finalMatrix ) {
// match column names to the samples. can have any order so be careful.
List<String> colNames = rawMatrix.getColNames();
Map<String, BioMaterial> bmMap = new HashMap<String, BioMaterial>();
Collection<BioAssay> bioAssays = ee.getBioAssays();
for ( BioAssay bioAssay : bioAssays ) {
Collection<BioMaterial> samplesUsed = bioAssay.getSamplesUsed();
assert samplesUsed.size() == 1;
BioMaterial bm = samplesUsed.iterator().next();
if ( bmMap.containsKey( bm.getName() ) ) {
// this might not actually be an error - but just in case...
throw new IllegalStateException( "Two biomaterials from the same experiment with the same name " );
}
bmMap.put( bm.getName(), bm );
if ( bioAssay.getAccession() != null ) {
// e.g. GSM123455
String accession = bioAssay.getAccession().getAccession();
if ( bmMap.containsKey( accession ) ) {
throw new IllegalStateException( "Two bioassays with the same accession" );
}
bmMap.put( accession, bm );
}
// I think it will always be null, if it is from GEO anyway.
if ( bm.getExternalAccession() != null ) {
if ( bmMap.containsKey( bm.getExternalAccession().getAccession() ) ) {
throw new IllegalStateException( "Two biomaterials with the same accession" );
}
bmMap.put( bm.getExternalAccession().getAccession(), bm );
}
}
List<BioMaterial> newColNames = new ArrayList<BioMaterial>();
for ( String colName : colNames ) {
BioMaterial bm = bmMap.get( colName );
if ( bm == null ) {
throw new IllegalStateException( "Could not match a column name to a biomaterial: " + colName );
}
newColNames.add( bm );
}
finalMatrix.setColumnNames( newColNames );
}
/**
* @param targetArrayDesign
* @param rawMatrix
* @return matrix with row names fixed up. ColumnNames still need to be done.
*/
private DoubleMatrix<CompositeSequence, BioMaterial> matchElementsToRowNames( ArrayDesign targetArrayDesign,
DoubleMatrix<String, String> rawMatrix ) {
Map<String, CompositeSequence> pnmap = new HashMap<String, CompositeSequence>();
for ( CompositeSequence cs : targetArrayDesign.getCompositeSequences() ) {
pnmap.put( cs.getName(), cs );
}
int failedMatch = 0;
int timesWarned = 0;
List<CompositeSequence> newRowNames = new ArrayList<CompositeSequence>();
List<String> usableRowNames = new ArrayList<String>();
for ( String rowName : rawMatrix.getRowNames() ) {
CompositeSequence cs = pnmap.get( rowName );
if ( cs == null ) {
/*
* This might be okay, but we not too much
*/
failedMatch++;
if ( timesWarned < 20 ) {
log.warn( "No platform match to element named: " + rowName );
}
if ( timesWarned == 20 ) {
log.warn( "Further warnings suppressed" );
}
timesWarned++;
}
usableRowNames.add( rowName );
newRowNames.add( cs );
}
if ( usableRowNames.isEmpty() ) {
throw new IllegalArgumentException( "None of the rows matched the given platform elements" );
}
DoubleMatrix<CompositeSequence, BioMaterial> finalMatrix;
if ( failedMatch > 0 ) {
log.warn( failedMatch + "/" + rawMatrix.rows()
+ " elements could not be matched to the platform. Lines that did not match will be ignore." );
DoubleMatrix<String, String> useableData = rawMatrix.subsetRows( usableRowNames );
finalMatrix = new DenseDoubleMatrix<CompositeSequence, BioMaterial>( useableData.getRawMatrix() );
} else {
finalMatrix = new DenseDoubleMatrix<CompositeSequence, BioMaterial>( rawMatrix.getRawMatrix() );
finalMatrix.setRowNames( newRowNames );
}
return finalMatrix; // not completel final.
}
/**
* determine the target array design. We use filtered versions of these platforms from GEO.
*
* @param primaryTaxon
* @return
*/
private ArrayDesign prepareTargetPlatformForExonArrays( Taxon primaryTaxon ) {
/*
* Unfortunately there is no way to get around hard-coding this, in some way; there are specific platforms we
* need to use.
*/
String targetPlatformAcc = "";
if ( primaryTaxon.getCommonName().equals( "mouse" ) ) {
targetPlatformAcc = "GPL6096";
} else if ( primaryTaxon.getCommonName().equals( "human" ) ) {
targetPlatformAcc = "GPL5175"; // [HuEx-1_0-st] Affymetrix Human Exon 1.0 ST Array [transcript (gene)
// version]
} else if ( primaryTaxon.getCommonName().equals( "rat" ) ) {
targetPlatformAcc = "GPL6543";
} else {
throw new IllegalArgumentException( "Exon arrays only supported for mouse, human and rat" );
}
ArrayDesign targetPlatform = arrayDesignService.findByShortName( targetPlatformAcc );
if ( targetPlatform != null ) {
targetPlatform = arrayDesignService.thaw( targetPlatform );
if ( targetPlatform.getCompositeSequences().isEmpty() ) {
/*
* Ok, we have to 'reload it' and add the compositeSequences.
*/
geoService.addElements( targetPlatform );
}
} else {
log.warn( "The target platform " + targetPlatformAcc + " could not be found in the system. Loading it ..." );
Collection<?> r = geoService.fetchAndLoad( targetPlatformAcc, true, false, false, false );
if ( r.isEmpty() ) throw new IllegalStateException( "Loading target platform failed." );
targetPlatform = ( ArrayDesign ) r.iterator().next();
}
return targetPlatform;
}
}
| gemma-core/src/main/java/ubic/gemma/loader/expression/geo/DataUpdater.java | /*
* The Gemma project
*
* Copyright (c) 2012 University of British Columbia
*
* 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 ubic.gemma.loader.expression.geo;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ubic.basecode.dataStructure.matrix.DenseDoubleMatrix;
import ubic.basecode.dataStructure.matrix.DoubleMatrix;
import ubic.basecode.io.ByteArrayConverter;
import ubic.basecode.math.DescriptiveWithMissing;
import ubic.gemma.analysis.expression.AnalysisUtilService;
import ubic.gemma.analysis.preprocess.ProcessedExpressionDataVectorCreateService;
import ubic.gemma.analysis.preprocess.SampleCoexpressionMatrixService;
import ubic.gemma.analysis.preprocess.svd.SVDService;
import ubic.gemma.datastructure.matrix.ExpressionDataDoubleMatrix;
import ubic.gemma.expression.experiment.service.ExpressionExperimentService;
import ubic.gemma.loader.expression.AffyPowerToolsProbesetSummarize;
import ubic.gemma.loader.expression.geo.fetcher.RawDataFetcher;
import ubic.gemma.loader.expression.geo.service.GeoService;
import ubic.gemma.model.common.auditAndSecurity.AuditTrailService;
import ubic.gemma.model.common.auditAndSecurity.eventType.AuditEventType;
import ubic.gemma.model.common.auditAndSecurity.eventType.DataAddedEvent;
import ubic.gemma.model.common.auditAndSecurity.eventType.DataReplacedEvent;
import ubic.gemma.model.common.auditAndSecurity.eventType.ExpressionExperimentPlatformSwitchEvent;
import ubic.gemma.model.common.description.LocalFile;
import ubic.gemma.model.common.description.VocabCharacteristic;
import ubic.gemma.model.common.quantitationtype.GeneralType;
import ubic.gemma.model.common.quantitationtype.PrimitiveType;
import ubic.gemma.model.common.quantitationtype.QuantitationType;
import ubic.gemma.model.common.quantitationtype.ScaleType;
import ubic.gemma.model.common.quantitationtype.StandardQuantitationType;
import ubic.gemma.model.expression.arrayDesign.ArrayDesign;
import ubic.gemma.model.expression.arrayDesign.ArrayDesignService;
import ubic.gemma.model.expression.bioAssay.BioAssay;
import ubic.gemma.model.expression.bioAssay.BioAssayService;
import ubic.gemma.model.expression.bioAssayData.BioAssayDimension;
import ubic.gemma.model.expression.bioAssayData.BioAssayDimensionService;
import ubic.gemma.model.expression.bioAssayData.RawExpressionDataVector;
import ubic.gemma.model.expression.biomaterial.BioMaterial;
import ubic.gemma.model.expression.biomaterial.BioMaterialService;
import ubic.gemma.model.expression.designElement.CompositeSequence;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.genome.Taxon;
import cern.colt.list.DoubleArrayList;
/**
* Update the data associated with an experiment. Primary designed for filling in data that we can't or don't want to
* get from GEO. For loading experiments from flat files, see SimpleExpressionDataLoaderService
*
* @author paul
* @version $Id$
*/
@Component
public class DataUpdater {
private static Log log = LogFactory.getLog( DataUpdater.class );
@Autowired
private ArrayDesignService arrayDesignService;
@Autowired
private BioAssayDimensionService assayDimensionService;
@Autowired
private BioMaterialService bioMaterialService;
@Autowired
private BioAssayService bioAssayService;
@Autowired
private AuditTrailService auditTrailService;
@Autowired
private ExpressionExperimentService experimentService;
@Autowired
private AnalysisUtilService analysisUtilService;
@Autowired
private GeoService geoService;
@Autowired
private ProcessedExpressionDataVectorCreateService processedExpressionDataVectorCreateService;
@Autowired
private SampleCoexpressionMatrixService sampleCoexpressionMatrixService;
@Autowired
private SVDService svdService;
public ExpressionExperiment addAffyExonArrayData( ExpressionExperiment ee ) {
Collection<ArrayDesign> ads = experimentService.getArrayDesignsUsed( ee );
if ( ads.size() > 1 ) {
throw new IllegalArgumentException( "Can't handle experiments with more than one platform" );
}
return addAffyExonArrayData( ee, ads.iterator().next() );
}
/**
* Replaces any existing "preferred" dat.
*
* @param ee
* @param ad
*/
public ExpressionExperiment addAffyExonArrayData( ExpressionExperiment ee, ArrayDesign ad ) {
RawDataFetcher f = new RawDataFetcher();
Collection<LocalFile> files = f.fetch( ee.getAccession().getAccession() );
if ( files.isEmpty() ) {
throw new RuntimeException( "Data was apparently not available" );
}
ad = arrayDesignService.thaw( ad );
ee = experimentService.thawLite( ee );
Taxon primaryTaxon = ad.getPrimaryTaxon();
ArrayDesign targetPlatform = prepareTargetPlatformForExonArrays( primaryTaxon );
assert !targetPlatform.getCompositeSequences().isEmpty();
AffyPowerToolsProbesetSummarize apt = new AffyPowerToolsProbesetSummarize();
Collection<RawExpressionDataVector> vectors = apt.processExonArrayData( ee, targetPlatform, files );
if ( vectors.isEmpty() ) {
throw new IllegalStateException( "No vectors were returned for " + ee );
}
ee = experimentService.replaceVectors( ee, targetPlatform, vectors );
if ( !targetPlatform.equals( ad ) ) {
AuditEventType eventType = ExpressionExperimentPlatformSwitchEvent.Factory.newInstance();
auditTrailService.addUpdateEvent( ee, eventType,
"Switched in course of updating vectors using AffyPowerTools (from " + ad.getShortName() + " to "
+ targetPlatform.getShortName() + ")" );
}
audit( ee, "Data vector computation from CEL files using AffyPowerTools for " + targetPlatform, true );
postprocess( ee );
return ee;
}
/**
* Use when we want to avoid downloading the CEL files etc. For example if GEO doesn't have them and we ran
* apt-probeset-summarize ourselves.
*
* @param ee
* @param pathToAptOutputFile
* @throws IOException
* @throws FileNotFoundException
*/
public void addAffyExonArrayData( ExpressionExperiment ee, String pathToAptOutputFile )
throws FileNotFoundException, IOException {
Collection<ArrayDesign> ads = experimentService.getArrayDesignsUsed( ee );
if ( ads.size() > 1 ) {
throw new IllegalArgumentException( "Can't handle experiments with more than one platform" );
}
ArrayDesign ad = ads.iterator().next();
ad = arrayDesignService.thaw( ad );
ee = experimentService.thawLite( ee );
Taxon primaryTaxon = ad.getPrimaryTaxon();
ArrayDesign targetPlatform = prepareTargetPlatformForExonArrays( primaryTaxon );
AffyPowerToolsProbesetSummarize apt = new AffyPowerToolsProbesetSummarize();
Collection<RawExpressionDataVector> vectors = apt
.processExonArrayData( ee, pathToAptOutputFile, targetPlatform );
if ( vectors.isEmpty() ) {
throw new IllegalStateException( "No vectors were returned for " + ee );
}
experimentService.replaceVectors( ee, targetPlatform, vectors );
if ( !targetPlatform.equals( ad ) ) {
AuditEventType eventType = ExpressionExperimentPlatformSwitchEvent.Factory.newInstance();
auditTrailService.addUpdateEvent( ee, eventType,
"Switched in course of updating vectors using AffyPowerTools (from " + ad.getShortName() + " to "
+ targetPlatform.getShortName() + ")" );
}
audit( ee, "Data vector input from APT output file " + pathToAptOutputFile + " on " + targetPlatform, true );
postprocess( ee );
}
/**
* Add an additional data (with associated quantitation type) to the selected experiment. Will do postprocessing if
* the data quantitationtype is 'preferred', but if there is already a preferred quantitation type, an error will be
* thrown.
*
* @param ee
* @param targetPlatform
* @param data
*/
public ExpressionExperiment addData( ExpressionExperiment ee, ArrayDesign targetPlatform,
ExpressionDataDoubleMatrix data ) {
Collection<ArrayDesign> ads = experimentService.getArrayDesignsUsed( ee );
if ( ads.size() > 1 ) {
throw new IllegalArgumentException( "Can only replace data for an experiment that uses one platform; "
+ "you must switch/merge first and then provide appropriate replacement data." );
}
if ( data.rows() == 0 ) {
throw new IllegalArgumentException( "Data had no rows" );
}
ArrayDesign originalArrayDesign = ads.iterator().next();
if ( !targetPlatform.equals( originalArrayDesign ) ) {
throw new IllegalArgumentException(
"You can only add data for a platform that already is used for the experiment: "
+ originalArrayDesign + " != targeted " + targetPlatform );
}
Collection<QuantitationType> qts = data.getQuantitationTypes();
if ( qts.size() > 1 ) {
throw new IllegalArgumentException( "Only support a single quantitation type" );
}
if ( qts.isEmpty() ) {
throw new IllegalArgumentException( "Please supply a quantitation type with the data" );
}
QuantitationType qt = qts.iterator().next();
if ( qt.getIsPreferred() ) {
for ( QuantitationType existingQt : ee.getQuantitationTypes() ) {
if ( existingQt.getIsPreferred() ) {
throw new IllegalArgumentException(
"You cannot add 'preferred' data to an experiment that already has it. You should first make the existing data non-preferred." );
}
}
}
Collection<RawExpressionDataVector> vectors = makeNewVectors( ee, targetPlatform, data, qt );
if ( vectors.isEmpty() ) {
throw new IllegalStateException( "no vectors!" );
}
ee = experimentService.addVectors( ee, originalArrayDesign, vectors );
audit( ee, "Data vectors added for " + targetPlatform + ", " + qt, false );
if ( qt.getIsPreferred() ) {
postprocess( ee );
}
// debug code.
for ( BioAssay ba : ee.getBioAssays() ) {
assert ba.getArrayDesignUsed().equals( targetPlatform );
}
experimentService.update( ee );
return ee;
}
/**
* @param ee
* @param qt
* @return
*/
public int deleteData( ExpressionExperiment ee, QuantitationType qt ) {
return this.experimentService.removeData( ee, qt );
}
/**
* @param ee
*/
public void postprocess( ExpressionExperiment ee ) {
processedExpressionDataVectorCreateService.computeProcessedExpressionData( ee );
sampleCoexpressionMatrixService.delete( ee );
sampleCoexpressionMatrixService.create( ee, true );
svdService.svd( ee.getId() );
}
/**
* Replace the data associated with the experiment (or add it if there is none). These data become the 'preferred'
* quantitation type.
* <p>
* Similar to AffyPowerToolsProbesetSummarize.convertDesignElementDataVectors and code in
* SimpleExpressionDataLoaderService.
*
* @param ee the experiment to be modified
* @param targetPlatform the platform for the new data
* @param data the data to be used
*/
public ExpressionExperiment replaceData( ExpressionExperiment ee, ArrayDesign targetPlatform,
ExpressionDataDoubleMatrix data ) {
Collection<ArrayDesign> ads = experimentService.getArrayDesignsUsed( ee );
if ( ads.size() > 1 ) {
throw new IllegalArgumentException( "Can only replace data for an experiment that uses one platform; "
+ "you must switch/merge first and then provide appropriate replacement data." );
}
if ( data.rows() == 0 ) {
throw new IllegalArgumentException( "Data had no rows" );
}
ArrayDesign originalArrayDesign = ads.iterator().next();
Collection<QuantitationType> qts = data.getQuantitationTypes();
if ( qts.size() > 1 ) {
throw new IllegalArgumentException( "Only support a single quantitation type" );
}
if ( qts.isEmpty() ) {
throw new IllegalArgumentException( "Please supply a quantitation type with the data" );
}
QuantitationType qt = qts.iterator().next();
qt.setIsPreferred( true );
Collection<RawExpressionDataVector> vectors = makeNewVectors( ee, targetPlatform, data, qt );
if ( vectors.isEmpty() ) {
throw new IllegalStateException( "no vectors!" );
}
/*
* delete all analyses, etc.
*/
analysisUtilService.deleteOldAnalyses( ee );
ee = experimentService.replaceVectors( ee, targetPlatform, vectors );
// audit if we switched platforms.
if ( !targetPlatform.equals( originalArrayDesign ) ) {
AuditEventType eventType = ExpressionExperimentPlatformSwitchEvent.Factory.newInstance();
auditTrailService.addUpdateEvent(
ee,
eventType,
"Switched in course of updating vectors using data input (from "
+ originalArrayDesign.getShortName() + " to " + targetPlatform.getShortName() + ")" );
}
audit( ee, "Data vector replacement for " + targetPlatform, true );
postprocess( ee );
// debug code.
for ( BioAssay ba : ee.getBioAssays() ) {
assert ba.getArrayDesignUsed().equals( targetPlatform );
}
experimentService.update( ee );
return ee;
}
/**
* Replaces data.
*
* @param ee
* @param targetArrayDesign
* @param countMatrix Representing 'raw' counts (added after rpkm, if provided), which is treated as the 'preferred'
* data. If this is provided, all the other data will be removed.
* @param rpkmMatrix Representing per-gene normalized data, optional.
*/
public void addCountDataMatricesToExperiment( ExpressionExperiment ee, ArrayDesign targetArrayDesign,
DoubleMatrix<String, String> countMatrix, DoubleMatrix<String, String> rpkmMatrix ) {
// make the proper matrices we need for loading.
if ( countMatrix == null )
throw new IllegalArgumentException( "You must provide count matrix (rpkm is optional)" );
targetArrayDesign = arrayDesignService.thaw( targetArrayDesign );
/*
* Treat this as the preferred data, so we have to do it first.
*/
DoubleMatrix<CompositeSequence, BioMaterial> properCountMatrix = matchElementsToRowNames( targetArrayDesign,
countMatrix );
matchBioMaterialsToColNames( ee, countMatrix, properCountMatrix );
QuantitationType countqt = makeQt( true );
countqt.setName( "Counts" );
countqt.setDescription( "Read counts" );
countqt.setIsBackgroundSubtracted( false );
countqt.setIsNormalized( false );
ExpressionDataDoubleMatrix countEEMatrix = new ExpressionDataDoubleMatrix( ee, countqt, properCountMatrix );
ee = replaceData( ee, targetArrayDesign, countEEMatrix );
addTotalCountInformation( ee, countEEMatrix );
if ( rpkmMatrix != null ) {
DoubleMatrix<CompositeSequence, BioMaterial> properRPKMMatrix = matchElementsToRowNames( targetArrayDesign,
rpkmMatrix );
matchBioMaterialsToColNames( ee, rpkmMatrix, properRPKMMatrix );
QuantitationType rpkmqt = makeQt( false );
rpkmqt.setIsRatio( false );
rpkmqt.setName( "RPKM" );
rpkmqt.setDescription( "Reads (or fragments) per kb of gene model per million reads" );
rpkmqt.setIsBackgroundSubtracted( false );
rpkmqt.setIsNormalized( true );
ExpressionDataDoubleMatrix rpkmEEMatrix = new ExpressionDataDoubleMatrix( ee, rpkmqt, properRPKMMatrix );
ee = addData( ee, targetArrayDesign, rpkmEEMatrix );
}
}
/**
* @param ee
* @param countEEMatrix
*/
private void addTotalCountInformation( ExpressionExperiment ee, ExpressionDataDoubleMatrix countEEMatrix ) {
for ( BioAssay ba : ee.getBioAssays() ) {
Double[] col = countEEMatrix.getColumn( ba );
double librarySize = DescriptiveWithMissing.sum( new DoubleArrayList( ArrayUtils.toPrimitive( col ) ) );
// Ideally also know read length.
ba.setDescription( ba.getDescription() + " totalCounts=" + Math.floor( librarySize ) );
// This isn't a very good place to keep this...
VocabCharacteristic countTerm = VocabCharacteristic.Factory.newInstance();
countTerm.setName( "LibrarySize" );
countTerm.setDescription( "Total read counts in sample, computed from the imported data." );
// this is really a placeholder.
countTerm.setCategory( "count" );
countTerm.setCategoryUri( "http://purl.obolibrary.org/obo/PATO_0000070" );
countTerm.setValue( String.format( "%d", ( int ) Math.floor( librarySize ) ) );
BioMaterial bm = ba.getSamplesUsed().iterator().next();
bm.getCharacteristics().add( countTerm );
bioMaterialService.update( bm );
bioAssayService.update( ba );
}
}
/**
* @param ee
* @param note
* @param replace if true, use a DataReplacedEvent; otherwise DataAddedEvent.
*/
private void audit( ExpressionExperiment ee, String note, boolean replace ) {
AuditEventType eventType = null;
if ( replace ) {
eventType = DataReplacedEvent.Factory.newInstance();
} else {
eventType = DataAddedEvent.Factory.newInstance();
}
auditTrailService.addUpdateEvent( ee, eventType, note );
}
/**
* @param ee
* @param targetPlatform
* @param data
* @param qt
* @return
*/
private Collection<RawExpressionDataVector> makeNewVectors( ExpressionExperiment ee, ArrayDesign targetPlatform,
ExpressionDataDoubleMatrix data, QuantitationType qt ) {
ByteArrayConverter bArrayConverter = new ByteArrayConverter();
Collection<RawExpressionDataVector> vectors = new HashSet<RawExpressionDataVector>();
BioAssayDimension bioAssayDimension = data.getBestBioAssayDimension();
assert bioAssayDimension != null;
assert !bioAssayDimension.getBioAssays().isEmpty();
bioAssayDimension = assayDimensionService.findOrCreate( bioAssayDimension );
assert !bioAssayDimension.getBioAssays().isEmpty();
for ( int i = 0; i < data.rows(); i++ ) {
byte[] bdata = bArrayConverter.doubleArrayToBytes( data.getRow( i ) );
RawExpressionDataVector vector = RawExpressionDataVector.Factory.newInstance();
vector.setData( bdata );
CompositeSequence cs = data.getRowElement( i ).getDesignElement();
if ( cs == null ) {
continue;
}
if ( !cs.getArrayDesign().equals( targetPlatform ) ) {
throw new IllegalArgumentException( "Input data must use the target platform (was: "
+ cs.getArrayDesign() + ", expected: " + targetPlatform );
}
vector.setDesignElement( cs );
vector.setQuantitationType( qt );
vector.setExpressionExperiment( ee );
vector.setBioAssayDimension( bioAssayDimension );
vectors.add( vector );
}
return vectors;
}
/**
* @param preferred
* @return
*/
private QuantitationType makeQt( boolean preferred ) {
QuantitationType qt = QuantitationType.Factory.newInstance();
qt.setGeneralType( GeneralType.QUANTITATIVE );
qt.setScale( ScaleType.LINEAR );
qt.setIsBackground( false );
qt.setIsRatio( false );
qt.setIsBackgroundSubtracted( true );
qt.setIsNormalized( true );
qt.setIsMaskedPreferred( true );
qt.setIsPreferred( preferred );
qt.setIsBatchCorrected( false );
qt.setType( StandardQuantitationType.AMOUNT );
qt.setRepresentation( PrimitiveType.DOUBLE );
return qt;
}
/**
* @param ee
* @param rawMatrix
* @param finalMatrix
*/
private void matchBioMaterialsToColNames( ExpressionExperiment ee, DoubleMatrix<String, String> rawMatrix,
DoubleMatrix<CompositeSequence, BioMaterial> finalMatrix ) {
// match column names to the samples. can have any order so be careful.
List<String> colNames = rawMatrix.getColNames();
Map<String, BioMaterial> bmMap = new HashMap<String, BioMaterial>();
Collection<BioAssay> bioAssays = ee.getBioAssays();
for ( BioAssay bioAssay : bioAssays ) {
Collection<BioMaterial> samplesUsed = bioAssay.getSamplesUsed();
assert samplesUsed.size() == 1;
BioMaterial bm = samplesUsed.iterator().next();
if ( bmMap.containsKey( bm.getName() ) ) {
// this might not actually be an error - but just in case...
throw new IllegalStateException( "Two biomaterials from the same experiment with the same name " );
}
bmMap.put( bm.getName(), bm );
if ( bioAssay.getAccession() != null ) {
// e.g. GSM123455
String accession = bioAssay.getAccession().getAccession();
if ( bmMap.containsKey( accession ) ) {
throw new IllegalStateException( "Two bioassays with the same accession" );
}
bmMap.put( accession, bm );
}
// I think it will always be null, if it is from GEO anyway.
if ( bm.getExternalAccession() != null ) {
if ( bmMap.containsKey( bm.getExternalAccession().getAccession() ) ) {
throw new IllegalStateException( "Two biomaterials with the same accession" );
}
bmMap.put( bm.getExternalAccession().getAccession(), bm );
}
}
List<BioMaterial> newColNames = new ArrayList<BioMaterial>();
for ( String colName : colNames ) {
BioMaterial bm = bmMap.get( colName );
if ( bm == null ) {
throw new IllegalStateException( "Could not match a column name to a biomaterial: " + colName );
}
newColNames.add( bm );
}
finalMatrix.setColumnNames( newColNames );
}
/**
* @param targetArrayDesign
* @param rawMatrix
* @return matrix with row names fixed up. ColumnNames still need to be done.
*/
private DoubleMatrix<CompositeSequence, BioMaterial> matchElementsToRowNames( ArrayDesign targetArrayDesign,
DoubleMatrix<String, String> rawMatrix ) {
Map<String, CompositeSequence> pnmap = new HashMap<String, CompositeSequence>();
for ( CompositeSequence cs : targetArrayDesign.getCompositeSequences() ) {
pnmap.put( cs.getName(), cs );
}
int failedMatch = 0;
int timesWarned = 0;
List<CompositeSequence> newRowNames = new ArrayList<CompositeSequence>();
List<String> usableRowNames = new ArrayList<String>();
for ( String rowName : rawMatrix.getRowNames() ) {
CompositeSequence cs = pnmap.get( rowName );
if ( cs == null ) {
/*
* This might be okay, but we not too much
*/
failedMatch++;
if ( timesWarned < 20 ) {
log.warn( "No platform match to element named: " + rowName );
timesWarned++;
}
if ( timesWarned == 20 ) {
log.warn( "Further warnings suppressed" );
}
}
usableRowNames.add( rowName );
newRowNames.add( cs );
}
if ( usableRowNames.isEmpty() ) {
throw new IllegalArgumentException( "None of the rows matched the given platform elements" );
}
DoubleMatrix<CompositeSequence, BioMaterial> finalMatrix;
if ( failedMatch > 0 ) {
log.warn( failedMatch + "/" + rawMatrix.rows()
+ " elements could not be matched to the platform. Lines that did not match will be ignore." );
DoubleMatrix<String, String> useableData = rawMatrix.subsetRows( usableRowNames );
finalMatrix = new DenseDoubleMatrix<CompositeSequence, BioMaterial>( useableData.getRawMatrix() );
} else {
finalMatrix = new DenseDoubleMatrix<CompositeSequence, BioMaterial>( rawMatrix.getRawMatrix() );
finalMatrix.setRowNames( newRowNames );
}
return finalMatrix; // not completel final.
}
/**
* determine the target array design. We use filtered versions of these platforms from GEO.
*
* @param primaryTaxon
* @return
*/
private ArrayDesign prepareTargetPlatformForExonArrays( Taxon primaryTaxon ) {
/*
* Unfortunately there is no way to get around hard-coding this, in some way; there are specific platforms we
* need to use.
*/
String targetPlatformAcc = "";
if ( primaryTaxon.getCommonName().equals( "mouse" ) ) {
targetPlatformAcc = "GPL6096";
} else if ( primaryTaxon.getCommonName().equals( "human" ) ) {
targetPlatformAcc = "GPL5175"; // [HuEx-1_0-st] Affymetrix Human Exon 1.0 ST Array [transcript (gene)
// version]
} else if ( primaryTaxon.getCommonName().equals( "rat" ) ) {
targetPlatformAcc = "GPL6543";
} else {
throw new IllegalArgumentException( "Exon arrays only supported for mouse, human and rat" );
}
ArrayDesign targetPlatform = arrayDesignService.findByShortName( targetPlatformAcc );
if ( targetPlatform != null ) {
targetPlatform = arrayDesignService.thaw( targetPlatform );
if ( targetPlatform.getCompositeSequences().isEmpty() ) {
/*
* Ok, we have to 'reload it' and add the compositeSequences.
*/
geoService.addElements( targetPlatform );
}
} else {
log.warn( "The target platform " + targetPlatformAcc + " could not be found in the system. Loading it ..." );
Collection<?> r = geoService.fetchAndLoad( targetPlatformAcc, true, false, false, false );
if ( r.isEmpty() ) throw new IllegalStateException( "Loading target platform failed." );
targetPlatform = ( ArrayDesign ) r.iterator().next();
}
return targetPlatform;
}
}
| fix bug in logging.
| gemma-core/src/main/java/ubic/gemma/loader/expression/geo/DataUpdater.java | fix bug in logging. | <ide><path>emma-core/src/main/java/ubic/gemma/loader/expression/geo/DataUpdater.java
<ide> failedMatch++;
<ide> if ( timesWarned < 20 ) {
<ide> log.warn( "No platform match to element named: " + rowName );
<del> timesWarned++;
<ide> }
<ide> if ( timesWarned == 20 ) {
<ide> log.warn( "Further warnings suppressed" );
<ide> }
<add> timesWarned++;
<ide> }
<ide> usableRowNames.add( rowName );
<ide> newRowNames.add( cs ); |
|
Java | apache-2.0 | 6305bdc69fec99a60d58592e795ecffecf88e44e | 0 | eitchnet/strolch,eitchnet/strolch,4treesCH/strolch,eitchnet/strolch,4treesCH/strolch,4treesCH/strolch,eitchnet/strolch,4treesCH/strolch | /*
* Copyright 2013 Robert von Burg <[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 ch.eitchnet.xmlpers.impl;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.eitchnet.utils.helper.StringHelper;
import ch.eitchnet.utils.objectfilter.ObjectFilter;
import ch.eitchnet.xmlpers.api.FileDao;
import ch.eitchnet.xmlpers.api.IoMode;
import ch.eitchnet.xmlpers.api.MetadataDao;
import ch.eitchnet.xmlpers.api.ModificationResult;
import ch.eitchnet.xmlpers.api.ObjectDao;
import ch.eitchnet.xmlpers.api.PersistenceContext;
import ch.eitchnet.xmlpers.api.PersistenceRealm;
import ch.eitchnet.xmlpers.api.PersistenceTransaction;
import ch.eitchnet.xmlpers.api.TransactionCloseStrategy;
import ch.eitchnet.xmlpers.api.TransactionResult;
import ch.eitchnet.xmlpers.api.TransactionState;
import ch.eitchnet.xmlpers.api.XmlPersistenceException;
import ch.eitchnet.xmlpers.objref.ObjectReferenceCache;
/**
* @author Robert von Burg <[email protected]>
*
*/
public class DefaultPersistenceTransaction implements PersistenceTransaction {
private static final Logger logger = LoggerFactory.getLogger(DefaultPersistenceTransaction.class);
private final DefaultPersistenceRealm realm;
private final boolean verbose;
private final ObjectFilter objectFilter;
private final ObjectDao objectDao;
private final MetadataDao metadataDao;
private FileDao fileDao;
private IoMode ioMode;
private TransactionCloseStrategy closeStrategy;
private TransactionState state;
private long startTime;
private Date startTimeDate;
private TransactionResult txResult;
public DefaultPersistenceTransaction(DefaultPersistenceRealm realm, boolean verbose) {
this.startTime = System.nanoTime();
this.startTimeDate = new Date();
this.realm = realm;
this.verbose = verbose;
this.objectFilter = new ObjectFilter();
this.fileDao = new FileDao(this, realm.getPathBuilder(), verbose);
this.objectDao = new ObjectDao(this, this.fileDao, this.objectFilter);
this.metadataDao = new MetadataDao(realm.getPathBuilder(), this, verbose);
this.closeStrategy = TransactionCloseStrategy.COMMIT;
this.state = TransactionState.OPEN;
}
@Override
public void setTransactionResult(TransactionResult txResult) throws IllegalStateException {
if (this.txResult != null) {
String msg = "The transaction already has a result set!"; //$NON-NLS-1$
throw new IllegalStateException(msg);
}
this.txResult = txResult;
}
@Override
public TransactionResult getTransactionResult() throws IllegalStateException {
if (isOpen()) {
String msg = "The transaction is still open thus has no result yet! Either commit or rollback before calling this method"; //$NON-NLS-1$
throw new IllegalStateException(msg);
}
return this.txResult;
}
@Override
public PersistenceRealm getRealm() {
return this.realm;
}
@Override
public ObjectDao getObjectDao() {
return this.objectDao;
}
@Override
public MetadataDao getMetadataDao() {
return this.metadataDao;
}
@Override
public ObjectReferenceCache getObjectRefCache() {
return this.realm.getObjectRefCache();
}
@Override
public void setCloseStrategy(TransactionCloseStrategy closeStrategy) {
this.closeStrategy = closeStrategy;
}
@Override
public void close() throws XmlPersistenceException {
this.closeStrategy.close(this);
}
@Override
public void autoCloseableRollback() {
long start = System.nanoTime();
if (this.state == TransactionState.COMMITTED)
throw new IllegalStateException("Transaction has already been committed!"); //$NON-NLS-1$
if (this.state != TransactionState.ROLLED_BACK) {
unlockObjectRefs();
this.state = TransactionState.ROLLED_BACK;
this.objectFilter.clearCache();
long end = System.nanoTime();
long txDuration = end - this.startTime;
long closeDuration = end - start;
this.txResult.clear();
this.txResult.setState(this.state);
this.txResult.setStartTime(this.startTimeDate);
this.txResult.setTxDuration(txDuration);
this.txResult.setCloseDuration(closeDuration);
this.txResult.setRealm(this.realm.getRealmName());
this.txResult.setModificationByKey(Collections.<String, ModificationResult> emptyMap());
}
}
@Override
public void autoCloseableCommit() throws XmlPersistenceException {
long start = System.nanoTime();
try {
if (this.verbose) {
String msg = "Committing {0} operations in TX...";//$NON-NLS-1$
logger.info(MessageFormat.format(msg, this.objectFilter.sizeCache()));
}
Set<String> keySet = this.objectFilter.keySet();
Map<String, ModificationResult> modifications;
if (this.txResult == null)
modifications = null;
else
modifications = new HashMap<>(keySet.size());
for (String key : keySet) {
List<Object> removed = this.objectFilter.getRemoved(key);
if (removed.isEmpty()) {
if (this.verbose)
logger.info("No objects removed in this tx."); //$NON-NLS-1$
} else {
if (this.verbose)
logger.info(removed.size() + " objects removed in this tx."); //$NON-NLS-1$
for (Object object : removed) {
@SuppressWarnings("unchecked")
PersistenceContext<Object> ctx = (PersistenceContext<Object>) object;
this.fileDao.performDelete(ctx);
}
}
List<Object> updated = this.objectFilter.getUpdated(key);
if (updated.isEmpty()) {
if (this.verbose)
logger.info("No objects updated in this tx."); //$NON-NLS-1$
} else {
if (this.verbose)
logger.info(updated.size() + " objects updated in this tx."); //$NON-NLS-1$
for (Object object : updated) {
@SuppressWarnings("unchecked")
PersistenceContext<Object> ctx = (PersistenceContext<Object>) object;
this.fileDao.performUpdate(ctx);
}
}
List<Object> added = this.objectFilter.getAdded(key);
if (added.isEmpty()) {
if (this.verbose)
logger.info("No objects added in this tx."); //$NON-NLS-1$
} else {
if (this.verbose)
logger.info(added.size() + " objects added in this tx."); //$NON-NLS-1$
for (Object object : added) {
@SuppressWarnings("unchecked")
PersistenceContext<Object> ctx = (PersistenceContext<Object>) object;
this.fileDao.performCreate(ctx);
}
}
if (modifications != null) {
ModificationResult result = new ModificationResult(key, added, updated, removed);
modifications.put(key, result);
}
}
if (this.txResult != null) {
this.txResult.clear();
this.txResult.setState(TransactionState.COMMITTED);
this.txResult.setModificationByKey(modifications);
}
} catch (Exception e) {
if (this.txResult == null) {
long end = System.nanoTime();
long txDuration = end - this.startTime;
long closeDuration = end - start;
StringBuilder sb = new StringBuilder();
sb.append("TX has failed after "); //$NON-NLS-1$
sb.append(StringHelper.formatNanoDuration(txDuration));
sb.append(" with close operation taking "); //$NON-NLS-1$
sb.append(StringHelper.formatNanoDuration(closeDuration));
logger.info(sb.toString());
throw e;
}
this.txResult.clear();
this.txResult.setState(TransactionState.FAILED);
this.txResult.setModificationByKey(Collections.<String, ModificationResult> emptyMap());
} finally {
// clean up
unlockObjectRefs();
this.objectFilter.clearCache();
}
long end = System.nanoTime();
long txDuration = end - this.startTime;
long closeDuration = end - start;
if (this.txResult == null) {
StringBuilder sb = new StringBuilder();
sb.append("TX was completed after "); //$NON-NLS-1$
sb.append(StringHelper.formatNanoDuration(txDuration));
sb.append(" with close operation taking "); //$NON-NLS-1$
sb.append(StringHelper.formatNanoDuration(closeDuration));
logger.info(sb.toString());
} else {
this.txResult.setStartTime(this.startTimeDate);
this.txResult.setTxDuration(txDuration);
this.txResult.setCloseDuration(closeDuration);
this.txResult.setRealm(this.realm.getRealmName());
if (this.txResult.getState() == TransactionState.FAILED) {
String msg = "Failed to commit TX due to underlying exception: {0}"; //$NON-NLS-1$
String causeMsg = this.txResult.getFailCause() == null ? null : this.txResult.getFailCause()
.getMessage();
msg = MessageFormat.format(msg, causeMsg);
throw new XmlPersistenceException(msg, this.txResult.getFailCause());
}
}
}
@SuppressWarnings("rawtypes")
private void unlockObjectRefs() {
List<PersistenceContext> lockedObjects = this.objectFilter.getAll(PersistenceContext.class);
for (PersistenceContext lockedObject : lockedObjects) {
lockedObject.getObjectRef().unlock();
}
}
@Override
public boolean isOpen() {
return this.state == TransactionState.OPEN;
}
@Override
public void setIoMode(IoMode ioMode) {
this.ioMode = ioMode;
}
@Override
public IoMode getIoMode() {
return this.ioMode;
}
}
| src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java | /*
* Copyright 2013 Robert von Burg <[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 ch.eitchnet.xmlpers.impl;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.eitchnet.utils.helper.StringHelper;
import ch.eitchnet.utils.objectfilter.ObjectFilter;
import ch.eitchnet.xmlpers.api.FileDao;
import ch.eitchnet.xmlpers.api.IoMode;
import ch.eitchnet.xmlpers.api.MetadataDao;
import ch.eitchnet.xmlpers.api.ModificationResult;
import ch.eitchnet.xmlpers.api.ObjectDao;
import ch.eitchnet.xmlpers.api.PersistenceContext;
import ch.eitchnet.xmlpers.api.PersistenceRealm;
import ch.eitchnet.xmlpers.api.PersistenceTransaction;
import ch.eitchnet.xmlpers.api.TransactionCloseStrategy;
import ch.eitchnet.xmlpers.api.TransactionResult;
import ch.eitchnet.xmlpers.api.TransactionState;
import ch.eitchnet.xmlpers.api.XmlPersistenceException;
import ch.eitchnet.xmlpers.objref.ObjectReferenceCache;
/**
* @author Robert von Burg <[email protected]>
*
*/
public class DefaultPersistenceTransaction implements PersistenceTransaction {
private static final Logger logger = LoggerFactory.getLogger(DefaultPersistenceTransaction.class);
private final DefaultPersistenceRealm realm;
private final boolean verbose;
private final ObjectFilter objectFilter;
private final ObjectDao objectDao;
private final MetadataDao metadataDao;
private FileDao fileDao;
private IoMode ioMode;
private TransactionCloseStrategy closeStrategy;
private TransactionState state;
private long startTime;
private Date startTimeDate;
private TransactionResult txResult;
public DefaultPersistenceTransaction(DefaultPersistenceRealm realm, boolean verbose) {
this.startTime = System.nanoTime();
this.startTimeDate = new Date();
this.realm = realm;
this.verbose = verbose;
this.objectFilter = new ObjectFilter();
this.fileDao = new FileDao(this, realm.getPathBuilder(), verbose);
this.objectDao = new ObjectDao(this, this.fileDao, this.objectFilter);
this.metadataDao = new MetadataDao(realm.getPathBuilder(), this, verbose);
this.closeStrategy = TransactionCloseStrategy.COMMIT;
this.state = TransactionState.OPEN;
}
@Override
public void setTransactionResult(TransactionResult txResult) throws IllegalStateException {
if (this.txResult != null) {
String msg = "The transaction already has a result set!"; //$NON-NLS-1$
throw new IllegalStateException(msg);
}
this.txResult = txResult;
}
@Override
public TransactionResult getTransactionResult() throws IllegalStateException {
if (isOpen()) {
String msg = "The transaction is still open thus has no result yet! Either commit or rollback before calling this method"; //$NON-NLS-1$
throw new IllegalStateException(msg);
}
return this.txResult;
}
@Override
public PersistenceRealm getRealm() {
return this.realm;
}
@Override
public ObjectDao getObjectDao() {
return this.objectDao;
}
@Override
public MetadataDao getMetadataDao() {
return this.metadataDao;
}
@Override
public ObjectReferenceCache getObjectRefCache() {
return this.realm.getObjectRefCache();
}
@Override
public void setCloseStrategy(TransactionCloseStrategy closeStrategy) {
this.closeStrategy = closeStrategy;
}
@Override
public void close() throws XmlPersistenceException {
this.closeStrategy.close(this);
}
@Override
public void autoCloseableRollback() {
long start = System.nanoTime();
if (this.state == TransactionState.COMMITTED)
throw new IllegalStateException("Transaction has already been committed!"); //$NON-NLS-1$
if (this.state != TransactionState.ROLLED_BACK) {
unlockObjectRefs();
this.state = TransactionState.ROLLED_BACK;
this.objectFilter.clearCache();
long end = System.nanoTime();
long txDuration = end - this.startTime;
long closeDuration = end - start;
this.txResult.clear();
this.txResult.setState(this.state);
this.txResult.setStartTime(this.startTimeDate);
this.txResult.setTxDuration(txDuration);
this.txResult.setCloseDuration(closeDuration);
this.txResult.setRealm(this.realm.getRealmName());
this.txResult.setModificationByKey(Collections.<String, ModificationResult> emptyMap());
}
}
@Override
public void autoCloseableCommit() throws XmlPersistenceException {
long start = System.nanoTime();
try {
if (this.verbose) {
String msg = "Committing {0} operations in TX...";//$NON-NLS-1$
logger.info(MessageFormat.format(msg, this.objectFilter.sizeCache()));
}
Set<String> keySet = this.objectFilter.keySet();
Map<String, ModificationResult> modifications;
if (this.txResult == null)
modifications = null;
else
modifications = new HashMap<>(keySet.size());
for (String key : keySet) {
List<Object> removed = this.objectFilter.getRemoved(key);
if (removed.isEmpty()) {
if (this.verbose)
logger.info("No objects removed in this tx."); //$NON-NLS-1$
} else {
if (this.verbose)
logger.info(removed.size() + " objects removed in this tx."); //$NON-NLS-1$
for (Object object : removed) {
@SuppressWarnings("unchecked")
PersistenceContext<Object> ctx = (PersistenceContext<Object>) object;
this.fileDao.performDelete(ctx);
}
}
List<Object> updated = this.objectFilter.getUpdated(key);
if (updated.isEmpty()) {
if (this.verbose)
logger.info("No objects updated in this tx."); //$NON-NLS-1$
} else {
if (this.verbose)
logger.info(updated.size() + " objects updated in this tx."); //$NON-NLS-1$
for (Object object : updated) {
@SuppressWarnings("unchecked")
PersistenceContext<Object> ctx = (PersistenceContext<Object>) object;
this.fileDao.performUpdate(ctx);
}
}
List<Object> added = this.objectFilter.getAdded(key);
if (added.isEmpty()) {
if (this.verbose)
logger.info("No objects added in this tx."); //$NON-NLS-1$
} else {
if (this.verbose)
logger.info(added.size() + " objects added in this tx."); //$NON-NLS-1$
for (Object object : added) {
@SuppressWarnings("unchecked")
PersistenceContext<Object> ctx = (PersistenceContext<Object>) object;
this.fileDao.performCreate(ctx);
}
}
if (modifications != null) {
ModificationResult result = new ModificationResult(key, added, updated, removed);
modifications.put(key, result);
}
}
if (this.txResult != null) {
this.txResult.clear();
this.txResult.setState(TransactionState.COMMITTED);
this.txResult.setModificationByKey(modifications);
}
} catch (Exception e) {
if (this.txResult == null) {
long end = System.nanoTime();
long txDuration = end - this.startTime;
long closeDuration = end - start;
StringBuilder sb = new StringBuilder();
sb.append("TX has failed after "); //$NON-NLS-1$
sb.append(StringHelper.formatNanoDuration(txDuration));
sb.append(" with close operation taking "); //$NON-NLS-1$
sb.append(StringHelper.formatNanoDuration(closeDuration));
logger.info(sb.toString());
throw e;
}
this.txResult.clear();
this.txResult.setState(TransactionState.FAILED);
this.txResult.setModificationByKey(Collections.<String, ModificationResult> emptyMap());
} finally {
// clean up
unlockObjectRefs();
this.objectFilter.clearCache();
}
long end = System.nanoTime();
long txDuration = end - this.startTime;
long closeDuration = end - start;
if (this.txResult == null) {
StringBuilder sb = new StringBuilder();
sb.append("TX was completed after "); //$NON-NLS-1$
sb.append(StringHelper.formatNanoDuration(txDuration));
sb.append(" with close operation taking "); //$NON-NLS-1$
sb.append(StringHelper.formatNanoDuration(closeDuration));
logger.info(sb.toString());
} else {
this.txResult.setStartTime(this.startTimeDate);
this.txResult.setTxDuration(txDuration);
this.txResult.setCloseDuration(closeDuration);
this.txResult.setRealm(this.realm.getRealmName());
if (this.txResult.getState() == TransactionState.FAILED) {
String msg = "Failed to commit TX due to underlying exception: {0}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, this.txResult.getFailCause().getMessage());
throw new XmlPersistenceException(msg, this.txResult.getFailCause());
}
}
}
@SuppressWarnings("rawtypes")
private void unlockObjectRefs() {
List<PersistenceContext> lockedObjects = this.objectFilter.getAll(PersistenceContext.class);
for (PersistenceContext lockedObject : lockedObjects) {
lockedObject.getObjectRef().unlock();
}
}
@Override
public boolean isOpen() {
return this.state == TransactionState.OPEN;
}
@Override
public void setIoMode(IoMode ioMode) {
this.ioMode = ioMode;
}
@Override
public IoMode getIoMode() {
return this.ioMode;
}
}
| [Minor] caught an NPE when the Transaction fails but no cause is set | src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java | [Minor] caught an NPE when the Transaction fails but no cause is set | <ide><path>rc/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java
<ide>
<ide> if (this.txResult.getState() == TransactionState.FAILED) {
<ide> String msg = "Failed to commit TX due to underlying exception: {0}"; //$NON-NLS-1$
<del> msg = MessageFormat.format(msg, this.txResult.getFailCause().getMessage());
<add> String causeMsg = this.txResult.getFailCause() == null ? null : this.txResult.getFailCause()
<add> .getMessage();
<add> msg = MessageFormat.format(msg, causeMsg);
<ide> throw new XmlPersistenceException(msg, this.txResult.getFailCause());
<ide> }
<ide> } |
|
Java | apache-2.0 | daf65a59e66d8fc3e64e024e94e61e3197015b30 | 0 | ryano144/intellij-community,wreckJ/intellij-community,supersven/intellij-community,holmes/intellij-community,supersven/intellij-community,semonte/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,izonder/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,fnouama/intellij-community,asedunov/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,slisson/intellij-community,consulo/consulo,lucafavatella/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,semonte/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,xfournet/intellij-community,dslomov/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,blademainer/intellij-community,robovm/robovm-studio,joewalnes/idea-community,clumsy/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,adedayo/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,retomerz/intellij-community,jagguli/intellij-community,hurricup/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ryano144/intellij-community,izonder/intellij-community,nicolargo/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,allotria/intellij-community,apixandru/intellij-community,da1z/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,supersven/intellij-community,da1z/intellij-community,holmes/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,slisson/intellij-community,asedunov/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,blademainer/intellij-community,fitermay/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ernestp/consulo,allotria/intellij-community,akosyakov/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,asedunov/intellij-community,diorcety/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,samthor/intellij-community,semonte/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,caot/intellij-community,apixandru/intellij-community,holmes/intellij-community,nicolargo/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,petteyg/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,da1z/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,semonte/intellij-community,suncycheng/intellij-community,holmes/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,apixandru/intellij-community,vladmm/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,diorcety/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,jexp/idea2,ernestp/consulo,petteyg/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,caot/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,petteyg/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,signed/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,consulo/consulo,Lekanich/intellij-community,petteyg/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,jagguli/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,supersven/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,signed/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,adedayo/intellij-community,fnouama/intellij-community,consulo/consulo,jagguli/intellij-community,fnouama/intellij-community,petteyg/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,vladmm/intellij-community,ibinti/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,signed/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,jexp/idea2,blademainer/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,adedayo/intellij-community,dslomov/intellij-community,izonder/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,diorcety/intellij-community,fnouama/intellij-community,robovm/robovm-studio,ibinti/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,supersven/intellij-community,kdwink/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,caot/intellij-community,kool79/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,jexp/idea2,fitermay/intellij-community,fnouama/intellij-community,ernestp/consulo,vladmm/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,holmes/intellij-community,xfournet/intellij-community,signed/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,clumsy/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,caot/intellij-community,youdonghai/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,blademainer/intellij-community,jexp/idea2,FHannes/intellij-community,izonder/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,jexp/idea2,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,jagguli/intellij-community,xfournet/intellij-community,slisson/intellij-community,samthor/intellij-community,amith01994/intellij-community,FHannes/intellij-community,ibinti/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,caot/intellij-community,petteyg/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,vladmm/intellij-community,blademainer/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,amith01994/intellij-community,izonder/intellij-community,kool79/intellij-community,signed/intellij-community,vladmm/intellij-community,petteyg/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,fitermay/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,signed/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,caot/intellij-community,vladmm/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,da1z/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,semonte/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,ahb0327/intellij-community,allotria/intellij-community,signed/intellij-community,da1z/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,jexp/idea2,vladmm/intellij-community,jexp/idea2,Lekanich/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,tmpgit/intellij-community,youdonghai/intellij-community,signed/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,signed/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,signed/intellij-community,ernestp/consulo,akosyakov/intellij-community,kool79/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,amith01994/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,da1z/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,FHannes/intellij-community,FHannes/intellij-community,allotria/intellij-community,amith01994/intellij-community,blademainer/intellij-community,hurricup/intellij-community,samthor/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,izonder/intellij-community,samthor/intellij-community,ibinti/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,consulo/consulo,apixandru/intellij-community,samthor/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,supersven/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,kool79/intellij-community,caot/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,holmes/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,supersven/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,ryano144/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,xfournet/intellij-community,caot/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,hurricup/intellij-community,joewalnes/idea-community,xfournet/intellij-community,jexp/idea2,mglukhikh/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,fitermay/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,ernestp/consulo,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,clumsy/intellij-community,samthor/intellij-community,kool79/intellij-community,kool79/intellij-community,signed/intellij-community,kdwink/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,holmes/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,robovm/robovm-studio,fnouama/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,slisson/intellij-community,retomerz/intellij-community,ryano144/intellij-community,clumsy/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,fnouama/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,izonder/intellij-community,ryano144/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,asedunov/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,amith01994/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,ryano144/intellij-community,asedunov/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,gnuhub/intellij-community,izonder/intellij-community,samthor/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,signed/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,consulo/consulo,fnouama/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,hurricup/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,caot/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community | /*
* @author max
*/
package com.intellij.psi.impl.compiled;
import com.intellij.lexer.JavaLexer;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiNameHelper;
import com.intellij.psi.PsiReferenceList;
import com.intellij.psi.impl.cache.ModifierFlags;
import com.intellij.psi.impl.cache.TypeInfo;
import com.intellij.psi.impl.java.stubs.*;
import com.intellij.psi.impl.java.stubs.impl.*;
import com.intellij.psi.stubs.PsiFileStub;
import com.intellij.psi.stubs.StubElement;
import com.intellij.util.ArrayUtil;
import com.intellij.util.cls.ClsFormatException;
import com.intellij.util.io.StringRef;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.*;
import org.objectweb.asm.commons.EmptyVisitor;
import java.io.IOException;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings({"HardCodedStringLiteral"})
public class ClsStubBuilder {
private ClsStubBuilder() {
}
@Nullable
public static PsiFileStub build(final VirtualFile vFile, byte[] bytes) throws ClsFormatException {
final ClsStubBuilderFactory[] factories = Extensions.getExtensions(ClsStubBuilderFactory.EP_NAME);
for (ClsStubBuilderFactory factory : factories) {
if (factory.canBeProcessed(vFile, bytes)) {
return factory.buildFileStub(vFile, bytes);
}
}
final PsiJavaFileStubImpl file = new PsiJavaFileStubImpl("dont.know.yet", true);
try {
final PsiClassStub result = buildClass(vFile, bytes, file, 0);
if (result == null) return null;
file.setPackageName(getPackageName(result));
}
catch (Exception e) {
throw new ClsFormatException();
}
return file;
}
private static PsiClassStub<?> buildClass(final VirtualFile vFile, final byte[] bytes, final StubElement parent, final int access) {
ClassReader reader = new ClassReader(bytes);
final MyClassVisitor classVisitor = new MyClassVisitor(vFile, parent, access);
reader.accept(classVisitor, ClassReader.SKIP_CODE);
return classVisitor.getResult();
}
private static String getPackageName(final PsiClassStub result) {
final String fqn = result.getQualifiedName();
final String shortName = result.getName();
if (fqn == null || Comparing.equal(shortName, fqn)) {
return "";
}
return fqn.substring(0, fqn.lastIndexOf('.'));
}
private static class MyClassVisitor implements ClassVisitor {
private final StubElement myParent;
private final int myAccess;
private final VirtualFile myVFile;
private PsiModifierListStub myModlist;
private PsiClassStub myResult;
@NonNls private static final String SYNTHETIC_CLINIT_METHOD = "<clinit>";
@NonNls private static final String SYNTHETIC_INIT_METHOD = "<init>";
private JavaLexer myLexer;
private MyClassVisitor(final VirtualFile vFile, final StubElement parent, final int access) {
myVFile = vFile;
myParent = parent;
myAccess = access;
}
public PsiClassStub<?> getResult() {
return myResult;
}
public void visit(final int version,
final int access,
final String name,
final String signature,
final String superName,
final String[] interfaces) {
String fqn = getClassName(name);
final String shortName = PsiNameHelper.getShortClassName(fqn);
final int flags = myAccess == 0 ? access : myAccess;
boolean isDeprecated = (flags & Opcodes.ACC_DEPRECATED) != 0;
boolean isInterface = (flags & Opcodes.ACC_INTERFACE) != 0;
boolean isEnum = (flags & Opcodes.ACC_ENUM) != 0;
boolean isAnnotationType = (flags & Opcodes.ACC_ANNOTATION) != 0;
final byte stubFlags = PsiClassStubImpl.packFlags(isDeprecated, isInterface, isEnum, false, false, isAnnotationType, false, false);
myResult = new PsiClassStubImpl(JavaStubElementTypes.CLASS, myParent, fqn, shortName, null, stubFlags);
LanguageLevel languageLevel = convertFromVersion(version);
myLexer = new JavaLexer(languageLevel);
((PsiClassStubImpl)myResult).setLanguageLevel(languageLevel);
myModlist = new PsiModifierListStubImpl(myResult, packModlistFlags(flags));
CharacterIterator signatureIterator = signature != null ? new StringCharacterIterator(signature) : null;
if (signatureIterator != null) {
try {
SignatureParsing.parseTypeParametersDeclaration(signatureIterator, myResult);
}
catch (ClsFormatException e) {
signatureIterator = null;
}
} else {
new PsiTypeParameterListStubImpl(myResult);
}
String convertedSuper;
List<String> convertedInterfaces = new ArrayList<String>();
if (signatureIterator == null) {
convertedSuper = parseClassDescription(superName, interfaces, convertedInterfaces);
} else {
try {
convertedSuper = parseClassSignature(signatureIterator, convertedInterfaces);
}
catch (ClsFormatException e) {
new PsiTypeParameterListStubImpl(myResult);
convertedSuper = parseClassDescription(superName, interfaces, convertedInterfaces);
}
}
String[] interfacesArray = ArrayUtil.toStringArray(convertedInterfaces);
if (isInterface) {
new PsiClassReferenceListStubImpl(JavaStubElementTypes.EXTENDS_LIST, myResult, interfacesArray, PsiReferenceList.Role.EXTENDS_LIST);
new PsiClassReferenceListStubImpl(JavaStubElementTypes.IMPLEMENTS_LIST, myResult, ArrayUtil.EMPTY_STRING_ARRAY,
PsiReferenceList.Role.IMPLEMENTS_LIST);
} else {
if (convertedSuper != null && !"java.lang.Object".equals(convertedSuper)) {
new PsiClassReferenceListStubImpl(JavaStubElementTypes.EXTENDS_LIST, myResult, new String[]{convertedSuper},
PsiReferenceList.Role.EXTENDS_LIST);
} else {
new PsiClassReferenceListStubImpl(JavaStubElementTypes.EXTENDS_LIST, myResult, ArrayUtil.EMPTY_STRING_ARRAY, PsiReferenceList.Role.EXTENDS_LIST);
}
new PsiClassReferenceListStubImpl(JavaStubElementTypes.IMPLEMENTS_LIST, myResult, interfacesArray,
PsiReferenceList.Role.IMPLEMENTS_LIST);
}
}
@Nullable
private static String parseClassDescription(final String superName, final String[] interfaces, final List<String> convertedInterfaces) {
final String convertedSuper = superName != null ? getClassName(superName) : null;
for (String anInterface : interfaces) {
convertedInterfaces.add(getClassName(anInterface));
}
return convertedSuper;
}
@Nullable
private static String parseClassSignature(final CharacterIterator signatureIterator, final List<String> convertedInterfaces)
throws ClsFormatException {
final String convertedSuper = SignatureParsing.parseToplevelClassRefSignature(signatureIterator);
while (signatureIterator.current() != CharacterIterator.DONE) {
final String ifs = SignatureParsing.parseToplevelClassRefSignature(signatureIterator);
if (ifs == null) throw new ClsFormatException();
convertedInterfaces.add(ifs);
}
return convertedSuper;
}
private static LanguageLevel convertFromVersion(final int version) {
if (version == Opcodes.V1_1 || version == Opcodes.V1_2 || version == Opcodes.V1_3) {
return LanguageLevel.JDK_1_3;
}
if (version == Opcodes.V1_4) {
return LanguageLevel.JDK_1_4;
}
if (version == Opcodes.V1_5 || version == Opcodes.V1_6) {
return LanguageLevel.JDK_1_5;
}
return LanguageLevel.HIGHEST;
}
private static int packModlistFlags(final int access) {
int flags = 0;
if ((access & Opcodes.ACC_PRIVATE) != 0) {
flags |= ModifierFlags.PRIVATE_MASK;
} else if ((access & Opcodes.ACC_PROTECTED) != 0) {
flags |= ModifierFlags.PROTECTED_MASK;
} else if ((access & Opcodes.ACC_PUBLIC) != 0) {
flags |= ModifierFlags.PUBLIC_MASK;
} else {
flags |= ModifierFlags.PACKAGE_LOCAL_MASK;
}
if ((access & Opcodes.ACC_ABSTRACT) != 0) {
flags |= ModifierFlags.ABSTRACT_MASK;
}
if ((access & Opcodes.ACC_FINAL) != 0) {
flags |= ModifierFlags.FINAL_MASK;
}
if ((access & Opcodes.ACC_NATIVE) != 0) {
flags |= ModifierFlags.NATIVE_MASK;
}
if ((access & Opcodes.ACC_STATIC) != 0) {
flags |= ModifierFlags.STATIC_MASK;
}
if ((access & Opcodes.ACC_TRANSIENT) != 0) {
flags |= ModifierFlags.TRANSIENT_MASK;
}
if ((access & Opcodes.ACC_VOLATILE) != 0) {
flags |= ModifierFlags.VOLATILE_MASK;
}
if ((access & Opcodes.ACC_STRICT) != 0) {
flags |= ModifierFlags.STRICTFP_MASK;
}
return flags;
}
public void visitSource(final String source, final String debug) {
((PsiClassStubImpl)myResult).setSourceFileName(source);
}
public void visitOuterClass(final String owner, final String name, final String desc) {
}
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
return new AnnotationTextCollector(desc, new AnnotationResultCallback() {
public void callback(final String text) {
new PsiAnnotationStubImpl(myModlist, text);
}
});
}
public void visitAttribute(final Attribute attr) {
}
public void visitInnerClass(final String name, final String outerName, final String innerName, final int access) {
if ((access & Opcodes.ACC_SYNTHETIC) != 0) return;
if (!isCorrectName(innerName)) return;
if (innerName != null && outerName != null && getClassName(outerName).equals(myResult.getQualifiedName())) {
final String basename = myVFile.getNameWithoutExtension();
final VirtualFile dir = myVFile.getParent();
assert dir != null;
final VirtualFile innerFile = dir.findChild(basename + "$" + innerName + ".class");
if (innerFile != null) {
try {
buildClass(innerFile, innerFile.contentsToByteArray(), myResult, access);
}
catch (IOException e) {
// No inner class file found, ignore.
}
}
}
}
private boolean isCorrectName(String name) {
if (name == null) return false;
myLexer.start(name, 0, name.length(), 0);
if (myLexer.getTokenType() != JavaTokenType.IDENTIFIER) return false;
myLexer.advance();
return myLexer.getTokenType() == null;
}
public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, final Object value) {
if ((access & Opcodes.ACC_SYNTHETIC) != 0) return null;
if (!isCorrectName(name)) return null;
final byte flags = PsiFieldStubImpl.packFlags((access & Opcodes.ACC_ENUM) != 0, (access & Opcodes.ACC_DEPRECATED) != 0, false);
PsiFieldStub stub = new PsiFieldStubImpl(myResult, name, fieldType(desc, signature), constToString(value), flags);
final PsiModifierListStub modlist = new PsiModifierListStubImpl(stub, packModlistFlags(access));
return new AnnotationCollectingVisitor(stub, modlist);
}
private static TypeInfo fieldType(String desc, String signature) {
if (signature != null) {
try {
return TypeInfo.fromString(SignatureParsing.parseTypeString(new StringCharacterIterator(signature, 0)));
}
catch (ClsFormatException e) {
return fieldTypeViaDescription(desc);
}
} else {
return fieldTypeViaDescription(desc);
}
}
private static TypeInfo fieldTypeViaDescription(final String desc) {
Type type = Type.getType(desc);
final int dim = type.getSort() == Type.ARRAY ? type.getDimensions() : 0;
if (dim > 0) {
type = type.getElementType();
}
return new TypeInfo(StringRef.fromString(getTypeText(type)), (byte)dim, false);
}
@Nullable
public MethodVisitor visitMethod(final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions) {
if ((access & Opcodes.ACC_SYNTHETIC) != 0) return null;
if ((access & Opcodes.ACC_BRIDGE) != 0) return null;
if (SYNTHETIC_CLINIT_METHOD.equals(name)) return null;
boolean isDeprecated = (access & Opcodes.ACC_DEPRECATED) != 0;
boolean isConstructor = SYNTHETIC_INIT_METHOD.equals(name);
boolean isVarargs = (access & Opcodes.ACC_VARARGS) != 0;
boolean isAnnotationMethod = myResult.isAnnotationType();
if (!isConstructor && !isCorrectName(name)) return null;
final byte flags = PsiMethodStubImpl.packFlags(isConstructor, isAnnotationMethod, isVarargs, isDeprecated, false);
String canonicalMethodName = isConstructor ? myResult.getName() : name;
PsiMethodStubImpl stub = new PsiMethodStubImpl(myResult, canonicalMethodName, null, flags, null);
PsiModifierListStub modlist = new PsiModifierListStubImpl(stub, packMethodFlags(access));
String returnType;
List<String> args = new ArrayList<String>();
List<String> throwables = exceptions != null ? new ArrayList<String>() : null;
boolean parsedViaGenericSignature = false;
if (signature == null) {
returnType = parseMethodViaDescription(desc, stub, args);
} else {
try {
returnType = parseMethodViaGenericSignature(signature, stub, args, throwables);
parsedViaGenericSignature = true;
}
catch (ClsFormatException e) {
returnType = parseMethodViaDescription(desc, stub, args);
}
}
stub.setReturnType(TypeInfo.fromString(returnType));
boolean nonStaticInnerClassConstructor =
isConstructor && !parsedViaGenericSignature && !(myParent instanceof PsiFileStub) && (myModlist.getModifiersMask() & Opcodes.ACC_STATIC) == 0;
final PsiParameterListStubImpl parameterList = new PsiParameterListStubImpl(stub);
final int paramCount = args.size();
for (int i = 0; i < paramCount; i++) {
if (nonStaticInnerClassConstructor && i == 0) continue;
String arg = args.get(i);
boolean isEllipsisParam = isVarargs && i == paramCount - 1;
final TypeInfo typeInfo = TypeInfo.fromString(arg, isEllipsisParam);
PsiParameterStubImpl parameterStub = new PsiParameterStubImpl(parameterList, "p" + (i + 1), typeInfo, isEllipsisParam);
new PsiModifierListStubImpl(parameterStub, 0);
}
String[] thrownTypes = buildThrowsList(exceptions, throwables, parsedViaGenericSignature);
new PsiClassReferenceListStubImpl(JavaStubElementTypes.THROWS_LIST, stub, thrownTypes, PsiReferenceList.Role.THROWS_LIST);
return new AnnotationCollectingVisitor(stub, modlist);
}
private static String[] buildThrowsList(String[] exceptions, List<String> throwables, boolean parsedViaGenericSignature) {
if (exceptions == null) return ArrayUtil.EMPTY_STRING_ARRAY;
if (parsedViaGenericSignature) {
return throwables.toArray(new String[throwables.size()]);
}
else {
String[] converted = ArrayUtil.newStringArray(exceptions.length);
for (int i = 0; i < converted.length; i++) {
converted[i] = getClassName(exceptions[i]);
}
return converted;
}
}
private static int packMethodFlags(final int access) {
int commonFlags = packModlistFlags(access);
if ((access & Opcodes.ACC_SYNCHRONIZED) != 0) {
commonFlags |= ModifierFlags.SYNCHRONIZED_MASK;
}
return commonFlags;
}
private static String parseMethodViaDescription(final String desc, final PsiMethodStubImpl stub, final List<String> args) {
final String returnType = getTypeText(Type.getReturnType(desc));
final Type[] argTypes = Type.getArgumentTypes(desc);
for (Type argType : argTypes) {
args.add(getTypeText(argType));
}
new PsiTypeParameterListStubImpl(stub);
return returnType;
}
private static String parseMethodViaGenericSignature(final String signature,
final PsiMethodStubImpl stub,
final List<String> args,
final List<String> throwables)
throws ClsFormatException {
StringCharacterIterator iterator = new StringCharacterIterator(signature);
SignatureParsing.parseTypeParametersDeclaration(iterator, stub);
if (iterator.current() != '(') {
throw new ClsFormatException();
}
iterator.next();
while (iterator.current() != ')' && iterator.current() != CharacterIterator.DONE) {
args.add(SignatureParsing.parseTypeString(iterator));
}
if (iterator.current() != ')') {
throw new ClsFormatException();
}
iterator.next();
String returnType = SignatureParsing.parseTypeString(iterator);
while (iterator.current() == '^') {
iterator.next();
throwables.add(SignatureParsing.parseTypeString(iterator));
}
return returnType;
}
public void visitEnd() {
}
}
private static class AnnotationTextCollector implements AnnotationVisitor {
private final StringBuilder myBuilder = new StringBuilder();
private final AnnotationResultCallback myCallback;
private boolean hasParams = false;
private final String myDesc;
public AnnotationTextCollector(@Nullable String desc, AnnotationResultCallback callback) {
myCallback = callback;
myDesc = desc;
if (desc != null) {
myBuilder.append('@').append(getTypeText(Type.getType(desc)));
}
}
public void visit(final String name, final Object value) {
valuePairPrefix(name);
myBuilder.append(constToString(value));
}
public void visitEnum(final String name, final String desc, final String value) {
valuePairPrefix(name);
myBuilder.append(getTypeText(Type.getType(desc))).append(".").append(value);
}
private void valuePairPrefix(final String name) {
if (!hasParams) {
hasParams = true;
if (myDesc != null) {
myBuilder.append('(');
}
} else {
myBuilder.append(',');
}
if (name != null && !"value".equals(name)) {
myBuilder.append(name).append('=');
}
}
public AnnotationVisitor visitAnnotation(final String name, final String desc) {
valuePairPrefix(name);
return new AnnotationTextCollector(desc, new AnnotationResultCallback() {
public void callback(final String text) {
myBuilder.append(text);
}
});
}
public AnnotationVisitor visitArray(final String name) {
valuePairPrefix(name);
myBuilder.append("{");
return new AnnotationTextCollector(null, new AnnotationResultCallback() {
public void callback(final String text) {
myBuilder.append(text).append('}');
}
});
}
public void visitEnd() {
if (hasParams && myDesc != null) {
myBuilder.append(')');
}
myCallback.callback(myBuilder.toString());
}
}
private static class AnnotationCollectingVisitor extends EmptyVisitor {
private final StubElement myOwner;
private final PsiModifierListStub myModList;
private AnnotationCollectingVisitor(final StubElement owner, final PsiModifierListStub modList) {
myOwner = owner;
myModList = modList;
}
public AnnotationVisitor visitAnnotationDefault() {
return new AnnotationTextCollector(null, new AnnotationResultCallback() {
public void callback(final String text) {
((PsiMethodStubImpl)myOwner).setDefaultValueText(text);
}
});
}
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
return new AnnotationTextCollector(desc, new AnnotationResultCallback() {
public void callback(final String text) {
new PsiAnnotationStubImpl(myModList, text);
}
});
}
public AnnotationVisitor visitParameterAnnotation(final int parameter, final String desc, final boolean visible) {
return new AnnotationTextCollector(desc, new AnnotationResultCallback() {
public void callback(final String text) {
new PsiAnnotationStubImpl(((PsiMethodStub)myOwner).findParameter(parameter).getModList(), text);
}
});
}
}
@SuppressWarnings({"HardCodedStringLiteral"})
@Nullable
private static String constToString(final Object value) {
if (value == null) return null;
if (value instanceof String) return "\"" + StringUtil.escapeStringCharacters((String)value) + "\"";
if (value instanceof Integer || value instanceof Boolean) return value.toString();
if (value instanceof Long) return value.toString() + "L";
if (value instanceof Double) {
final double d = ((Double)value).doubleValue();
if (Double.isInfinite(d)) {
return d > 0 ? "1.0 / 0.0" : "-1.0 / 0.0";
} else if (Double.isNaN(d)) {
return "0.0d / 0.0";
}
return Double.toString(d);
}
if (value instanceof Float) {
final float v = ((Float)value).floatValue();
if (Float.isInfinite(v)) {
return v > 0 ? "1.0f / 0.0" : "-1.0f / 0.0";
} else if (Float.isNaN(v)) {
return "0.0f / 0.0";
} else {
return Float.toString(v) + "f";
}
}
return null;
}
private interface AnnotationResultCallback {
void callback(String text);
}
private static String getClassName(final String name) {
return getTypeText(Type.getObjectType(name));
}
private static String getTypeText(final Type type) {
final String raw = type.getClassName();
return raw.replace('$', '.');
}
}
| source/com/intellij/psi/impl/compiled/ClsStubBuilder.java | /*
* @author max
*/
package com.intellij.psi.impl.compiled;
import com.intellij.lexer.JavaLexer;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiNameHelper;
import com.intellij.psi.PsiReferenceList;
import com.intellij.psi.impl.cache.ModifierFlags;
import com.intellij.psi.impl.cache.TypeInfo;
import com.intellij.psi.impl.java.stubs.*;
import com.intellij.psi.impl.java.stubs.impl.*;
import com.intellij.psi.stubs.PsiFileStub;
import com.intellij.psi.stubs.StubElement;
import com.intellij.util.ArrayUtil;
import com.intellij.util.cls.ClsFormatException;
import com.intellij.util.io.StringRef;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.*;
import org.objectweb.asm.commons.EmptyVisitor;
import java.io.IOException;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings({"HardCodedStringLiteral"})
public class ClsStubBuilder {
private ClsStubBuilder() {
}
@Nullable
public static PsiFileStub build(final VirtualFile vFile, byte[] bytes) throws ClsFormatException {
final ClsStubBuilderFactory[] factories = Extensions.getExtensions(ClsStubBuilderFactory.EP_NAME);
for (ClsStubBuilderFactory factory : factories) {
if (factory.canBeProcessed(vFile, bytes)) {
return factory.buildFileStub(vFile, bytes);
}
}
final PsiJavaFileStubImpl file = new PsiJavaFileStubImpl("dont.know.yet", true);
try {
final PsiClassStub result = buildClass(vFile, bytes, file, 0);
if (result == null) return null;
file.setPackageName(getPackageName(result));
}
catch (Exception e) {
throw new ClsFormatException();
}
return file;
}
private static PsiClassStub<?> buildClass(final VirtualFile vFile, final byte[] bytes, final StubElement parent, final int access) {
ClassReader reader = new ClassReader(bytes);
final MyClassVisitor classVisitor = new MyClassVisitor(vFile, parent, access);
reader.accept(classVisitor, ClassReader.SKIP_CODE);
return classVisitor.getResult();
}
private static String getPackageName(final PsiClassStub result) {
final String fqn = result.getQualifiedName();
final String shortName = result.getName();
if (fqn == null || Comparing.equal(shortName, fqn)) {
return "";
}
return fqn.substring(0, fqn.lastIndexOf('.'));
}
private static class MyClassVisitor implements ClassVisitor {
private final StubElement myParent;
private final int myAccess;
private final VirtualFile myVFile;
private PsiModifierListStub myModlist;
private PsiClassStub myResult;
@NonNls private static final String SYNTHETIC_CLINIT_METHOD = "<clinit>";
@NonNls private static final String SYNTHETIC_INIT_METHOD = "<init>";
private JavaLexer myLexer;
private MyClassVisitor(final VirtualFile vFile, final StubElement parent, final int access) {
myVFile = vFile;
myParent = parent;
myAccess = access;
}
public PsiClassStub<?> getResult() {
return myResult;
}
public void visit(final int version,
final int access,
final String name,
final String signature,
final String superName,
final String[] interfaces) {
String fqn = getClassName(name);
final String shortName = PsiNameHelper.getShortClassName(fqn);
final int flags = myAccess == 0 ? access : myAccess;
boolean isDeprecated = (flags & Opcodes.ACC_DEPRECATED) != 0;
boolean isInterface = (flags & Opcodes.ACC_INTERFACE) != 0;
boolean isEnum = (flags & Opcodes.ACC_ENUM) != 0;
boolean isAnnotationType = (flags & Opcodes.ACC_ANNOTATION) != 0;
final byte stubFlags = PsiClassStubImpl.packFlags(isDeprecated, isInterface, isEnum, false, false, isAnnotationType, false, false);
myResult = new PsiClassStubImpl(JavaStubElementTypes.CLASS, myParent, fqn, shortName, null, stubFlags);
LanguageLevel languageLevel = convertFromVersion(version);
myLexer = new JavaLexer(languageLevel);
((PsiClassStubImpl)myResult).setLanguageLevel(languageLevel);
myModlist = new PsiModifierListStubImpl(myResult, packModlistFlags(flags));
CharacterIterator signatureIterator = signature != null ? new StringCharacterIterator(signature) : null;
if (signatureIterator != null) {
try {
SignatureParsing.parseTypeParametersDeclaration(signatureIterator, myResult);
}
catch (ClsFormatException e) {
signatureIterator = null;
}
} else {
new PsiTypeParameterListStubImpl(myResult);
}
String convertedSuper;
List<String> convertedInterfaces = new ArrayList<String>();
if (signatureIterator == null) {
convertedSuper = parseClassDescription(superName, interfaces, convertedInterfaces);
} else {
try {
convertedSuper = parseClassSignature(signatureIterator, convertedInterfaces);
}
catch (ClsFormatException e) {
new PsiTypeParameterListStubImpl(myResult);
convertedSuper = parseClassDescription(superName, interfaces, convertedInterfaces);
}
}
String[] interfacesArray = ArrayUtil.toStringArray(convertedInterfaces);
if (isInterface) {
new PsiClassReferenceListStubImpl(JavaStubElementTypes.EXTENDS_LIST, myResult, interfacesArray, PsiReferenceList.Role.EXTENDS_LIST);
new PsiClassReferenceListStubImpl(JavaStubElementTypes.IMPLEMENTS_LIST, myResult, ArrayUtil.EMPTY_STRING_ARRAY,
PsiReferenceList.Role.IMPLEMENTS_LIST);
} else {
if (convertedSuper != null && !"java.lang.Object".equals(convertedSuper)) {
new PsiClassReferenceListStubImpl(JavaStubElementTypes.EXTENDS_LIST, myResult, new String[]{convertedSuper},
PsiReferenceList.Role.EXTENDS_LIST);
} else {
new PsiClassReferenceListStubImpl(JavaStubElementTypes.EXTENDS_LIST, myResult, ArrayUtil.EMPTY_STRING_ARRAY, PsiReferenceList.Role.EXTENDS_LIST);
}
new PsiClassReferenceListStubImpl(JavaStubElementTypes.IMPLEMENTS_LIST, myResult, interfacesArray,
PsiReferenceList.Role.IMPLEMENTS_LIST);
}
}
@Nullable
private static String parseClassDescription(final String superName, final String[] interfaces, final List<String> convertedInterfaces) {
final String convertedSuper = superName != null ? getClassName(superName) : null;
for (String anInterface : interfaces) {
convertedInterfaces.add(getClassName(anInterface));
}
return convertedSuper;
}
@Nullable
private static String parseClassSignature(final CharacterIterator signatureIterator, final List<String> convertedInterfaces)
throws ClsFormatException {
final String convertedSuper = SignatureParsing.parseToplevelClassRefSignature(signatureIterator);
while (signatureIterator.current() != CharacterIterator.DONE) {
final String ifs = SignatureParsing.parseToplevelClassRefSignature(signatureIterator);
if (ifs == null) throw new ClsFormatException();
convertedInterfaces.add(ifs);
}
return convertedSuper;
}
private static LanguageLevel convertFromVersion(final int version) {
if (version == Opcodes.V1_1 || version == Opcodes.V1_2 || version == Opcodes.V1_3) {
return LanguageLevel.JDK_1_3;
}
if (version == Opcodes.V1_4) {
return LanguageLevel.JDK_1_4;
}
if (version == Opcodes.V1_5 || version == Opcodes.V1_6) {
return LanguageLevel.JDK_1_5;
}
return LanguageLevel.HIGHEST;
}
private static int packModlistFlags(final int access) {
int flags = 0;
if ((access & Opcodes.ACC_PRIVATE) != 0) {
flags |= ModifierFlags.PRIVATE_MASK;
} else if ((access & Opcodes.ACC_PROTECTED) != 0) {
flags |= ModifierFlags.PROTECTED_MASK;
} else if ((access & Opcodes.ACC_PUBLIC) != 0) {
flags |= ModifierFlags.PUBLIC_MASK;
} else {
flags |= ModifierFlags.PACKAGE_LOCAL_MASK;
}
if ((access & Opcodes.ACC_ABSTRACT) != 0) {
flags |= ModifierFlags.ABSTRACT_MASK;
}
if ((access & Opcodes.ACC_FINAL) != 0) {
flags |= ModifierFlags.FINAL_MASK;
}
if ((access & Opcodes.ACC_NATIVE) != 0) {
flags |= ModifierFlags.NATIVE_MASK;
}
if ((access & Opcodes.ACC_STATIC) != 0) {
flags |= ModifierFlags.STATIC_MASK;
}
if ((access & Opcodes.ACC_TRANSIENT) != 0) {
flags |= ModifierFlags.TRANSIENT_MASK;
}
if ((access & Opcodes.ACC_VOLATILE) != 0) {
flags |= ModifierFlags.VOLATILE_MASK;
}
if ((access & Opcodes.ACC_STRICT) != 0) {
flags |= ModifierFlags.STRICTFP_MASK;
}
return flags;
}
public void visitSource(final String source, final String debug) {
((PsiClassStubImpl)myResult).setSourceFileName(source);
}
public void visitOuterClass(final String owner, final String name, final String desc) {
}
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
return new AnnotationTextCollector(desc, new AnnotationResultCallback() {
public void callback(final String text) {
new PsiAnnotationStubImpl(myModlist, text);
}
});
}
public void visitAttribute(final Attribute attr) {
}
public void visitInnerClass(final String name, final String outerName, final String innerName, final int access) {
if ((access & Opcodes.ACC_SYNTHETIC) != 0) return;
if (!isCorrectName(innerName)) return;
if (innerName != null && outerName != null && getClassName(outerName).equals(myResult.getQualifiedName())) {
final String basename = myVFile.getNameWithoutExtension();
final VirtualFile dir = myVFile.getParent();
assert dir != null;
final VirtualFile innerFile = dir.findChild(basename + "$" + innerName + ".class");
if (innerFile != null) {
try {
buildClass(innerFile, innerFile.contentsToByteArray(), myResult, access);
}
catch (IOException e) {
// No inner class file found, ignore.
}
}
}
}
private boolean isCorrectName(String name) {
if (name == null) return false;
myLexer.start(name, 0, name.length(), 0);
if (myLexer.getTokenType() != JavaTokenType.IDENTIFIER) return false;
myLexer.advance();
return myLexer.getTokenType() == null;
}
public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, final Object value) {
if ((access & Opcodes.ACC_SYNTHETIC) != 0) return null;
if (!isCorrectName(name)) return null;
final byte flags = PsiFieldStubImpl.packFlags((access & Opcodes.ACC_ENUM) != 0, (access & Opcodes.ACC_DEPRECATED) != 0, false);
PsiFieldStub stub = new PsiFieldStubImpl(myResult, name, fieldType(desc, signature), constToString(value), flags);
final PsiModifierListStub modlist = new PsiModifierListStubImpl(stub, packModlistFlags(access));
return new AnnotationCollectingVisitor(stub, modlist);
}
private static TypeInfo fieldType(String desc, String signature) {
if (signature != null) {
try {
return TypeInfo.fromString(SignatureParsing.parseTypeString(new StringCharacterIterator(signature, 0)));
}
catch (ClsFormatException e) {
return fieldTypeViaDescription(desc);
}
} else {
return fieldTypeViaDescription(desc);
}
}
private static TypeInfo fieldTypeViaDescription(final String desc) {
Type type = Type.getType(desc);
final int dim = type.getSort() == Type.ARRAY ? type.getDimensions() : 0;
if (dim > 0) {
type = type.getElementType();
}
return new TypeInfo(StringRef.fromString(getTypeText(type)), (byte)dim, false);
}
@Nullable
public MethodVisitor visitMethod(final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions) {
if ((access & Opcodes.ACC_SYNTHETIC) != 0) return null;
if ((access & Opcodes.ACC_BRIDGE) != 0) return null;
if (SYNTHETIC_CLINIT_METHOD.equals(name)) return null;
boolean isDeprecated = (access & Opcodes.ACC_DEPRECATED) != 0;
boolean isConstructor = SYNTHETIC_INIT_METHOD.equals(name);
boolean isVarargs = (access & Opcodes.ACC_VARARGS) != 0;
boolean isAnnotationMethod = myResult.isAnnotationType();
if (!isConstructor && !isCorrectName(name)) return null;
final byte flags = PsiMethodStubImpl.packFlags(isConstructor, isAnnotationMethod, isVarargs, isDeprecated, false);
String canonicalMethodName = isConstructor ? myResult.getName() : name;
PsiMethodStubImpl stub = new PsiMethodStubImpl(myResult, canonicalMethodName, null, flags, null);
PsiModifierListStub modlist = new PsiModifierListStubImpl(stub, packMethodFlags(access));
String returnType;
List<String> args = new ArrayList<String>();
boolean parsedViaGenericSignature = false;
if (signature == null) {
returnType = parseMethodViaDescription(desc, stub, args);
} else {
try {
returnType = parseMethodViaGenericSignature(signature, stub, args);
parsedViaGenericSignature = true;
}
catch (ClsFormatException e) {
returnType = parseMethodViaDescription(desc, stub, args);
}
}
stub.setReturnType(TypeInfo.fromString(returnType));
boolean nonStaticInnerClassConstructor =
isConstructor && !parsedViaGenericSignature && !(myParent instanceof PsiFileStub) && (myModlist.getModifiersMask() & Opcodes.ACC_STATIC) == 0;
final PsiParameterListStubImpl parameterList = new PsiParameterListStubImpl(stub);
final int paramCount = args.size();
for (int i = 0; i < paramCount; i++) {
if (nonStaticInnerClassConstructor && i == 0) continue;
String arg = args.get(i);
boolean isEllipsisParam = isVarargs && i == paramCount - 1;
final TypeInfo typeInfo = TypeInfo.fromString(arg, isEllipsisParam);
PsiParameterStubImpl parameterStub = new PsiParameterStubImpl(parameterList, "p" + (i + 1), typeInfo, isEllipsisParam);
new PsiModifierListStubImpl(parameterStub, 0);
}
if (exceptions != null) {
String[] converted = ArrayUtil.newStringArray(exceptions.length);
for (int i = 0; i < converted.length; i++) {
converted[i] = getClassName(exceptions[i]);
}
new PsiClassReferenceListStubImpl(JavaStubElementTypes.THROWS_LIST, stub, converted, PsiReferenceList.Role.THROWS_LIST);
} else {
new PsiClassReferenceListStubImpl(JavaStubElementTypes.THROWS_LIST, stub, ArrayUtil.EMPTY_STRING_ARRAY, PsiReferenceList.Role.THROWS_LIST);
}
return new AnnotationCollectingVisitor(stub, modlist);
}
private static int packMethodFlags(final int access) {
int commonFlags = packModlistFlags(access);
if ((access & Opcodes.ACC_SYNCHRONIZED) != 0) {
commonFlags |= ModifierFlags.SYNCHRONIZED_MASK;
}
return commonFlags;
}
private static String parseMethodViaDescription(final String desc, final PsiMethodStubImpl stub, final List<String> args) {
final String returnType = getTypeText(Type.getReturnType(desc));
final Type[] argTypes = Type.getArgumentTypes(desc);
for (Type argType : argTypes) {
args.add(getTypeText(argType));
}
new PsiTypeParameterListStubImpl(stub);
return returnType;
}
private static String parseMethodViaGenericSignature(final String signature, final PsiMethodStubImpl stub, final List<String> args)
throws ClsFormatException {
StringCharacterIterator iterator = new StringCharacterIterator(signature);
SignatureParsing.parseTypeParametersDeclaration(iterator, stub);
if (iterator.current() != '(') {
throw new ClsFormatException();
}
iterator.next();
while (iterator.current() != ')' && iterator.current() != CharacterIterator.DONE) {
args.add(SignatureParsing.parseTypeString(iterator));
}
if (iterator.current() != ')') {
throw new ClsFormatException();
}
iterator.next();
return SignatureParsing.parseTypeString(iterator);
}
public void visitEnd() {
}
}
private static class AnnotationTextCollector implements AnnotationVisitor {
private final StringBuilder myBuilder = new StringBuilder();
private final AnnotationResultCallback myCallback;
private boolean hasParams = false;
private final String myDesc;
public AnnotationTextCollector(@Nullable String desc, AnnotationResultCallback callback) {
myCallback = callback;
myDesc = desc;
if (desc != null) {
myBuilder.append('@').append(getTypeText(Type.getType(desc)));
}
}
public void visit(final String name, final Object value) {
valuePairPrefix(name);
myBuilder.append(constToString(value));
}
public void visitEnum(final String name, final String desc, final String value) {
valuePairPrefix(name);
myBuilder.append(getTypeText(Type.getType(desc))).append(".").append(value);
}
private void valuePairPrefix(final String name) {
if (!hasParams) {
hasParams = true;
if (myDesc != null) {
myBuilder.append('(');
}
} else {
myBuilder.append(',');
}
if (name != null && !"value".equals(name)) {
myBuilder.append(name).append('=');
}
}
public AnnotationVisitor visitAnnotation(final String name, final String desc) {
valuePairPrefix(name);
return new AnnotationTextCollector(desc, new AnnotationResultCallback() {
public void callback(final String text) {
myBuilder.append(text);
}
});
}
public AnnotationVisitor visitArray(final String name) {
valuePairPrefix(name);
myBuilder.append("{");
return new AnnotationTextCollector(null, new AnnotationResultCallback() {
public void callback(final String text) {
myBuilder.append(text).append('}');
}
});
}
public void visitEnd() {
if (hasParams && myDesc != null) {
myBuilder.append(')');
}
myCallback.callback(myBuilder.toString());
}
}
private static class AnnotationCollectingVisitor extends EmptyVisitor {
private final StubElement myOwner;
private final PsiModifierListStub myModList;
private AnnotationCollectingVisitor(final StubElement owner, final PsiModifierListStub modList) {
myOwner = owner;
myModList = modList;
}
public AnnotationVisitor visitAnnotationDefault() {
return new AnnotationTextCollector(null, new AnnotationResultCallback() {
public void callback(final String text) {
((PsiMethodStubImpl)myOwner).setDefaultValueText(text);
}
});
}
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
return new AnnotationTextCollector(desc, new AnnotationResultCallback() {
public void callback(final String text) {
new PsiAnnotationStubImpl(myModList, text);
}
});
}
public AnnotationVisitor visitParameterAnnotation(final int parameter, final String desc, final boolean visible) {
return new AnnotationTextCollector(desc, new AnnotationResultCallback() {
public void callback(final String text) {
new PsiAnnotationStubImpl(((PsiMethodStub)myOwner).findParameter(parameter).getModList(), text);
}
});
}
}
@SuppressWarnings({"HardCodedStringLiteral"})
@Nullable
private static String constToString(final Object value) {
if (value == null) return null;
if (value instanceof String) return "\"" + StringUtil.escapeStringCharacters((String)value) + "\"";
if (value instanceof Integer || value instanceof Boolean) return value.toString();
if (value instanceof Long) return value.toString() + "L";
if (value instanceof Double) {
final double d = ((Double)value).doubleValue();
if (Double.isInfinite(d)) {
return d > 0 ? "1.0 / 0.0" : "-1.0 / 0.0";
} else if (Double.isNaN(d)) {
return "0.0d / 0.0";
}
return Double.toString(d);
}
if (value instanceof Float) {
final float v = ((Float)value).floatValue();
if (Float.isInfinite(v)) {
return v > 0 ? "1.0f / 0.0" : "-1.0f / 0.0";
} else if (Float.isNaN(v)) {
return "0.0f / 0.0";
} else {
return Float.toString(v) + "f";
}
}
return null;
}
private interface AnnotationResultCallback {
void callback(String text);
}
private static String getClassName(final String name) {
return getTypeText(Type.getObjectType(name));
}
private static String getTypeText(final Type type) {
final String raw = type.getClassName();
return raw.replace('$', '.');
}
} | IDEADEV-36385
| source/com/intellij/psi/impl/compiled/ClsStubBuilder.java | IDEADEV-36385 | <ide><path>ource/com/intellij/psi/impl/compiled/ClsStubBuilder.java
<ide>
<ide> String returnType;
<ide> List<String> args = new ArrayList<String>();
<add> List<String> throwables = exceptions != null ? new ArrayList<String>() : null;
<ide> boolean parsedViaGenericSignature = false;
<ide> if (signature == null) {
<ide> returnType = parseMethodViaDescription(desc, stub, args);
<ide> } else {
<ide> try {
<del> returnType = parseMethodViaGenericSignature(signature, stub, args);
<add> returnType = parseMethodViaGenericSignature(signature, stub, args, throwables);
<ide> parsedViaGenericSignature = true;
<ide> }
<ide> catch (ClsFormatException e) {
<ide> new PsiModifierListStubImpl(parameterStub, 0);
<ide> }
<ide>
<del> if (exceptions != null) {
<add> String[] thrownTypes = buildThrowsList(exceptions, throwables, parsedViaGenericSignature);
<add> new PsiClassReferenceListStubImpl(JavaStubElementTypes.THROWS_LIST, stub, thrownTypes, PsiReferenceList.Role.THROWS_LIST);
<add>
<add> return new AnnotationCollectingVisitor(stub, modlist);
<add> }
<add>
<add> private static String[] buildThrowsList(String[] exceptions, List<String> throwables, boolean parsedViaGenericSignature) {
<add> if (exceptions == null) return ArrayUtil.EMPTY_STRING_ARRAY;
<add> if (parsedViaGenericSignature) {
<add> return throwables.toArray(new String[throwables.size()]);
<add> }
<add> else {
<ide> String[] converted = ArrayUtil.newStringArray(exceptions.length);
<ide> for (int i = 0; i < converted.length; i++) {
<ide> converted[i] = getClassName(exceptions[i]);
<ide> }
<del> new PsiClassReferenceListStubImpl(JavaStubElementTypes.THROWS_LIST, stub, converted, PsiReferenceList.Role.THROWS_LIST);
<del> } else {
<del> new PsiClassReferenceListStubImpl(JavaStubElementTypes.THROWS_LIST, stub, ArrayUtil.EMPTY_STRING_ARRAY, PsiReferenceList.Role.THROWS_LIST);
<del> }
<del>
<del> return new AnnotationCollectingVisitor(stub, modlist);
<add> return converted;
<add> }
<ide> }
<ide>
<ide> private static int packMethodFlags(final int access) {
<ide> return returnType;
<ide> }
<ide>
<del> private static String parseMethodViaGenericSignature(final String signature, final PsiMethodStubImpl stub, final List<String> args)
<add> private static String parseMethodViaGenericSignature(final String signature,
<add> final PsiMethodStubImpl stub,
<add> final List<String> args,
<add> final List<String> throwables)
<ide> throws ClsFormatException {
<ide> StringCharacterIterator iterator = new StringCharacterIterator(signature);
<ide> SignatureParsing.parseTypeParametersDeclaration(iterator, stub);
<ide> }
<ide> iterator.next();
<ide>
<del> return SignatureParsing.parseTypeString(iterator);
<add> String returnType = SignatureParsing.parseTypeString(iterator);
<add>
<add> while (iterator.current() == '^') {
<add> iterator.next();
<add> throwables.add(SignatureParsing.parseTypeString(iterator));
<add> }
<add>
<add> return returnType;
<ide> }
<ide>
<ide> public void visitEnd() { |
|
Java | epl-1.0 | error: pathspec 'src/KthSmallestElementInBST.java' did not match any file(s) known to git
| 913e13c918c29d822460c90989c0291f0ebacea9 | 1 | cyanstone/LeetCode | import java.util.ArrayList;
import java.util.Stack;
public class KthSmallestElementInBST {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
private class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public int KthSmallest(TreeNode root ,int k) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode currentNode = root;
int count = 0;
while(currentNode != null || !stack.isEmpty()) {
if( currentNode != null) {
stack.push(currentNode);
currentNode = currentNode.left;
} else {
TreeNode node = stack.pop();
if(++count == k) return node.val;
currentNode = node.right;
}
}
return Integer.MIN_VALUE;
}
}
| src/KthSmallestElementInBST.java | 230. Kth Smallest Element in a BST | src/KthSmallestElementInBST.java | 230. Kth Smallest Element in a BST | <ide><path>rc/KthSmallestElementInBST.java
<add>import java.util.ArrayList;
<add>import java.util.Stack;
<add>
<add>
<add>public class KthSmallestElementInBST {
<add>
<add> public static void main(String[] args) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> private class TreeNode{
<add> int val;
<add> TreeNode left;
<add> TreeNode right;
<add> TreeNode(int x) { val = x; }
<add> }
<add>
<add> public int KthSmallest(TreeNode root ,int k) {
<add> Stack<TreeNode> stack = new Stack<TreeNode>();
<add> TreeNode currentNode = root;
<add> int count = 0;
<add> while(currentNode != null || !stack.isEmpty()) {
<add> if( currentNode != null) {
<add> stack.push(currentNode);
<add> currentNode = currentNode.left;
<add> } else {
<add> TreeNode node = stack.pop();
<add> if(++count == k) return node.val;
<add> currentNode = node.right;
<add> }
<add> }
<add> return Integer.MIN_VALUE;
<add> }
<add>
<add>} |
|
Java | apache-2.0 | 7accd9f3f98693c43b27b42ef3c6f087b025767c | 0 | dslomov/bazel,spxtr/bazel,hermione521/bazel,Asana/bazel,hermione521/bazel,damienmg/bazel,davidzchen/bazel,spxtr/bazel,meteorcloudy/bazel,ulfjack/bazel,snnn/bazel,dslomov/bazel,ulfjack/bazel,kchodorow/bazel-1,dslomov/bazel,davidzchen/bazel,dropbox/bazel,kchodorow/bazel-1,kchodorow/bazel,variac/bazel,dslomov/bazel-windows,hermione521/bazel,LuminateWireless/bazel,mikelikespie/bazel,dslomov/bazel-windows,spxtr/bazel,dslomov/bazel-windows,juhalindfors/bazel-patches,dropbox/bazel,aehlig/bazel,dslomov/bazel-windows,spxtr/bazel,dslomov/bazel-windows,hermione521/bazel,variac/bazel,akira-baruah/bazel,snnn/bazel,mikelikespie/bazel,juhalindfors/bazel-patches,safarmer/bazel,mbrukman/bazel,dslomov/bazel,mbrukman/bazel,twitter-forks/bazel,perezd/bazel,Asana/bazel,dropbox/bazel,meteorcloudy/bazel,kchodorow/bazel-1,zhexuany/bazel,akira-baruah/bazel,damienmg/bazel,variac/bazel,perezd/bazel,zhexuany/bazel,twitter-forks/bazel,Asana/bazel,snnn/bazel,safarmer/bazel,kchodorow/bazel,akira-baruah/bazel,bazelbuild/bazel,ButterflyNetwork/bazel,dslomov/bazel,twitter-forks/bazel,juhalindfors/bazel-patches,mikelikespie/bazel,zhexuany/bazel,damienmg/bazel,dslomov/bazel-windows,spxtr/bazel,safarmer/bazel,snnn/bazel,ulfjack/bazel,perezd/bazel,hermione521/bazel,juhalindfors/bazel-patches,bazelbuild/bazel,juhalindfors/bazel-patches,davidzchen/bazel,safarmer/bazel,werkt/bazel,mikelikespie/bazel,snnn/bazel,mbrukman/bazel,spxtr/bazel,ulfjack/bazel,perezd/bazel,katre/bazel,mikelikespie/bazel,katre/bazel,aehlig/bazel,ButterflyNetwork/bazel,aehlig/bazel,werkt/bazel,spxtr/bazel,dslomov/bazel,akira-baruah/bazel,cushon/bazel,ulfjack/bazel,twitter-forks/bazel,aehlig/bazel,meteorcloudy/bazel,Asana/bazel,dslomov/bazel,werkt/bazel,perezd/bazel,dropbox/bazel,mikelikespie/bazel,Asana/bazel,ulfjack/bazel,dropbox/bazel,damienmg/bazel,aehlig/bazel,twitter-forks/bazel,dropbox/bazel,bazelbuild/bazel,snnn/bazel,davidzchen/bazel,kchodorow/bazel-1,aehlig/bazel,twitter-forks/bazel,juhalindfors/bazel-patches,hermione521/bazel,variac/bazel,zhexuany/bazel,kchodorow/bazel,cushon/bazel,katre/bazel,mbrukman/bazel,LuminateWireless/bazel,davidzchen/bazel,katre/bazel,ulfjack/bazel,davidzchen/bazel,werkt/bazel,kchodorow/bazel,cushon/bazel,kchodorow/bazel,LuminateWireless/bazel,davidzchen/bazel,cushon/bazel,werkt/bazel,aehlig/bazel,bazelbuild/bazel,meteorcloudy/bazel,mbrukman/bazel,damienmg/bazel,damienmg/bazel,twitter-forks/bazel,kchodorow/bazel-1,variac/bazel,LuminateWireless/bazel,katre/bazel,kchodorow/bazel,akira-baruah/bazel,zhexuany/bazel,cushon/bazel,perezd/bazel,safarmer/bazel,ButterflyNetwork/bazel,ButterflyNetwork/bazel,juhalindfors/bazel-patches,cushon/bazel,Asana/bazel,katre/bazel,meteorcloudy/bazel,LuminateWireless/bazel,variac/bazel,damienmg/bazel,meteorcloudy/bazel,perezd/bazel,bazelbuild/bazel,akira-baruah/bazel,meteorcloudy/bazel,kchodorow/bazel-1,variac/bazel,safarmer/bazel,zhexuany/bazel,bazelbuild/bazel,snnn/bazel,mbrukman/bazel,LuminateWireless/bazel,werkt/bazel,kchodorow/bazel,ButterflyNetwork/bazel,ButterflyNetwork/bazel,Asana/bazel | // Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.android;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ResourceSet;
import com.google.devtools.build.lib.analysis.AnalysisUtils;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.OutputGroupProvider;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.analysis.actions.FileWriteAction;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.collect.IterablesChain;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.packages.AggregatingAttributeMapper;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.rules.android.AndroidResourcesProvider.ResourceContainer;
import com.google.devtools.build.lib.rules.android.AndroidResourcesProvider.ResourceType;
import com.google.devtools.build.lib.rules.android.AndroidRuleClasses.MultidexMode;
import com.google.devtools.build.lib.rules.cpp.CcLinkParams;
import com.google.devtools.build.lib.rules.cpp.CcLinkParamsProvider;
import com.google.devtools.build.lib.rules.cpp.CcLinkParamsStore;
import com.google.devtools.build.lib.rules.cpp.CcNativeLibraryProvider;
import com.google.devtools.build.lib.rules.cpp.CppFileTypes;
import com.google.devtools.build.lib.rules.cpp.LinkerInput;
import com.google.devtools.build.lib.rules.java.ClasspathConfiguredFragment;
import com.google.devtools.build.lib.rules.java.JavaCcLinkParamsProvider;
import com.google.devtools.build.lib.rules.java.JavaCommon;
import com.google.devtools.build.lib.rules.java.JavaCompilationArgs;
import com.google.devtools.build.lib.rules.java.JavaCompilationArgs.ClasspathType;
import com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider;
import com.google.devtools.build.lib.rules.java.JavaCompilationArtifacts;
import com.google.devtools.build.lib.rules.java.JavaCompilationHelper;
import com.google.devtools.build.lib.rules.java.JavaNativeLibraryProvider;
import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider;
import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider.OutputJar;
import com.google.devtools.build.lib.rules.java.JavaRuntimeJarProvider;
import com.google.devtools.build.lib.rules.java.JavaSemantics;
import com.google.devtools.build.lib.rules.java.JavaSourceJarsProvider;
import com.google.devtools.build.lib.rules.java.JavaTargetAttributes;
import com.google.devtools.build.lib.rules.java.JavaUtil;
import com.google.devtools.build.lib.rules.java.proto.GeneratedExtensionRegistryProvider;
import com.google.devtools.build.lib.rules.test.InstrumentedFilesCollector.InstrumentationSpec;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A helper class for android rules.
*
* <p>Helps create the java compilation as well as handling the exporting of the java compilation
* artifacts to the other rules.
*/
public class AndroidCommon {
public static final InstrumentationSpec ANDROID_COLLECTION_SPEC = JavaCommon.JAVA_COLLECTION_SPEC
.withDependencyAttributes("deps", "data", "exports", "runtime_deps", "binary_under_test");
public static final Set<String> TRANSITIVE_ATTRIBUTES = ImmutableSet.of(
"deps",
"exports"
);
public static final <T extends TransitiveInfoProvider> Iterable<T> getTransitivePrerequisites(
RuleContext ruleContext, Mode mode, final Class<T> classType) {
IterablesChain.Builder<T> builder = IterablesChain.builder();
for (String attr : TRANSITIVE_ATTRIBUTES) {
if (ruleContext.getAttribute(attr) != null) {
builder.add(ruleContext.getPrerequisites(attr, mode, classType));
}
}
return builder.build();
}
public static final Iterable<TransitiveInfoCollection> collectTransitiveInfo(
RuleContext ruleContext, Mode mode) {
ImmutableList.Builder<TransitiveInfoCollection> builder = ImmutableList.builder();
for (String attr : TRANSITIVE_ATTRIBUTES) {
if (ruleContext.getAttribute(attr) != null) {
builder.addAll(ruleContext.getPrerequisites(attr, mode));
}
}
return builder.build();
}
private final RuleContext ruleContext;
private final JavaCommon javaCommon;
private final boolean asNeverLink;
private final boolean exportDeps;
private NestedSet<Artifact> compileTimeDependencyArtifacts;
private NestedSet<Artifact> filesToBuild;
private NestedSet<Artifact> transitiveNeverlinkLibraries =
NestedSetBuilder.emptySet(Order.STABLE_ORDER);
private JavaCompilationArgs javaCompilationArgs = JavaCompilationArgs.EMPTY_ARGS;
private JavaCompilationArgs recursiveJavaCompilationArgs = JavaCompilationArgs.EMPTY_ARGS;
private JackCompilationHelper jackCompilationHelper;
private NestedSet<Artifact> jarsProducedForRuntime;
private Artifact classJar;
private Artifact iJar;
private Artifact srcJar;
private Artifact genClassJar;
private Artifact genSourceJar;
private Artifact resourceClassJar;
private Artifact resourceSourceJar;
private Artifact outputDepsProto;
private GeneratedExtensionRegistryProvider generatedExtensionRegistryProvider;
private final JavaSourceJarsProvider.Builder javaSourceJarsProviderBuilder =
JavaSourceJarsProvider.builder();
private final JavaRuleOutputJarsProvider.Builder javaRuleOutputJarsProviderBuilder =
JavaRuleOutputJarsProvider.builder();
private Artifact manifestProtoOutput;
private AndroidIdlHelper idlHelper;
public AndroidCommon(JavaCommon javaCommon) {
this(javaCommon, JavaCommon.isNeverLink(javaCommon.getRuleContext()), false);
}
/**
* Creates a new AndroidCommon.
* @param common the JavaCommon instance
* @param asNeverLink Boolean to indicate if this rule should be treated as a compile time dep
* by consuming rules.
* @param exportDeps Boolean to indicate if the dependencies should be treated as "exported" deps.
*/
public AndroidCommon(JavaCommon common, boolean asNeverLink, boolean exportDeps) {
this.ruleContext = common.getRuleContext();
this.asNeverLink = asNeverLink;
this.exportDeps = exportDeps;
this.javaCommon = common;
}
/**
* Collects the transitive neverlink dependencies.
*
* @param ruleContext the context of the rule neverlink deps are to be computed for
* @param deps the targets to be treated as dependencies
* @param runtimeJars the runtime jars produced by the rule (non-transitive)
*
* @return a nested set of the neverlink deps.
*/
public static NestedSet<Artifact> collectTransitiveNeverlinkLibraries(
RuleContext ruleContext, Iterable<? extends TransitiveInfoCollection> deps,
ImmutableList<Artifact> runtimeJars) {
NestedSetBuilder<Artifact> builder = NestedSetBuilder.naiveLinkOrder();
for (AndroidNeverLinkLibrariesProvider provider : AnalysisUtils.getProviders(deps,
AndroidNeverLinkLibrariesProvider.class)) {
builder.addTransitive(provider.getTransitiveNeverLinkLibraries());
}
if (JavaCommon.isNeverLink(ruleContext)) {
builder.addAll(runtimeJars);
for (JavaCompilationArgsProvider provider : AnalysisUtils.getProviders(
deps, JavaCompilationArgsProvider.class)) {
builder.addTransitive(provider.getRecursiveJavaCompilationArgs().getRuntimeJars());
}
}
return builder.build();
}
/**
* Creates an action that converts {@code jarToDex} to a dex file. The output will be stored in
* the {@link com.google.devtools.build.lib.actions.Artifact} {@code dxJar}.
*/
public static void createDexAction(
RuleContext ruleContext,
Artifact jarToDex, Artifact classesDex, List<String> dexOptions, boolean multidex,
Artifact mainDexList) {
List<String> args = new ArrayList<>();
args.add("--dex");
// Add --no-locals to coverage builds. Older coverage tools don't correctly preserve local
// variable information in stack frame maps that are required since Java 7, so to avoid runtime
// errors we just don't add local variable info in the first place. This may no longer be
// necessary, however, as long as we use a coverage tool that generates stack frame maps.
if (ruleContext.getConfiguration().isCodeCoverageEnabled()) {
args.add("--no-locals"); // TODO(bazel-team): Is this still needed?
}
// Multithreaded dex does not work when using --multi-dex.
if (!multidex) {
// Multithreaded dex tends to run faster, but only up to about 5 threads (at which point the
// law of diminishing returns kicks in). This was determined experimentally, with 5-thread dex
// performing about 25% faster than 1-thread dex.
args.add("--num-threads=5");
}
args.addAll(dexOptions);
if (multidex) {
args.add("--multi-dex");
if (mainDexList != null) {
args.add("--main-dex-list=" + mainDexList.getExecPathString());
}
}
args.add("--output=" + classesDex.getExecPathString());
args.add(jarToDex.getExecPathString());
SpawnAction.Builder builder = new SpawnAction.Builder()
.setExecutable(AndroidSdkProvider.fromRuleContext(ruleContext).getDx())
.addInput(jarToDex)
.addOutput(classesDex)
.addArguments(args)
.setProgressMessage("Converting " + jarToDex.getExecPathString() + " to dex format")
.setMnemonic("AndroidDexer")
.setResources(ResourceSet.createWithRamCpuIo(4096.0, 5.0, 0.0));
if (mainDexList != null) {
builder.addInput(mainDexList);
}
ruleContext.registerAction(builder.build(ruleContext));
}
public static AndroidIdeInfoProvider createAndroidIdeInfoProvider(
RuleContext ruleContext,
AndroidSemantics semantics,
AndroidIdlHelper idlHelper,
OutputJar resourceJar,
Artifact aar,
ResourceApk resourceApk,
Artifact zipAlignedApk,
Iterable<Artifact> apksUnderTest) {
AndroidIdeInfoProvider.Builder ideInfoProviderBuilder =
new AndroidIdeInfoProvider.Builder()
.setIdlClassJar(idlHelper.getIdlClassJar())
.setIdlSourceJar(idlHelper.getIdlSourceJar())
.setResourceJar(resourceJar)
.setAar(aar)
.addIdlImportRoot(idlHelper.getIdlImportRoot())
.addIdlParcelables(idlHelper.getIdlParcelables())
.addIdlSrcs(idlHelper.getIdlSources())
.addIdlGeneratedJavaFiles(idlHelper.getIdlGeneratedJavaSources())
.addAllApksUnderTest(apksUnderTest);
if (zipAlignedApk != null) {
ideInfoProviderBuilder.setApk(zipAlignedApk);
}
// If the rule defines resources, put those in the IDE info. Otherwise, proxy the data coming
// from the android_resources rule in its direct dependencies, if such a thing exists.
if (LocalResourceContainer.definesAndroidResources(ruleContext.attributes())) {
ideInfoProviderBuilder
.setDefinesAndroidResources(true)
.addResourceSources(resourceApk.getPrimaryResource().getArtifacts(ResourceType.RESOURCES))
.addAssetSources(
resourceApk.getPrimaryResource().getArtifacts(ResourceType.ASSETS),
getAssetDir(ruleContext))
// Sets the possibly merged manifest and the raw manifest.
.setGeneratedManifest(resourceApk.getPrimaryResource().getManifest())
.setManifest(ruleContext.getPrerequisiteArtifact("manifest", Mode.TARGET))
.setJavaPackage(getJavaPackage(ruleContext));
} else {
semantics.addNonLocalResources(ruleContext, resourceApk, ideInfoProviderBuilder);
}
return ideInfoProviderBuilder.build();
}
public static String getJavaPackage(RuleContext ruleContext) {
AttributeMap attributes = ruleContext.attributes();
if (attributes.isAttributeValueExplicitlySpecified("custom_package")) {
return attributes.get("custom_package", Type.STRING);
}
return getDefaultJavaPackage(ruleContext.getRule());
}
public static Iterable<String> getPossibleJavaPackages(Rule rule) {
AggregatingAttributeMapper attributes = AggregatingAttributeMapper.of(rule);
if (attributes.isAttributeValueExplicitlySpecified("custom_package")) {
return attributes.visitAttribute("custom_package", Type.STRING);
}
return ImmutableList.of(getDefaultJavaPackage(rule));
}
private static String getDefaultJavaPackage(Rule rule) {
PathFragment nameFragment = rule.getPackage().getNameFragment();
String packageName = JavaUtil.getJavaFullClassname(nameFragment);
if (packageName != null) {
return packageName;
} else {
// This is a workaround for libraries that don't follow the standard Bazel package format
return nameFragment.getPathString().replace('/', '.');
}
}
static PathFragment getSourceDirectoryRelativePathFromResource(Artifact resource) {
PathFragment resourceDir = LocalResourceContainer.Builder.findResourceDir(resource);
if (resourceDir == null) {
return null;
}
return trimTo(resource.getRootRelativePath(), resourceDir);
}
/**
* Finds the rightmost occurrence of the needle and returns subfragment of the haystack from
* left to the end of the occurrence inclusive of the needle.
*
* <pre>
* `Example:
* Given the haystack:
* res/research/handwriting/res/values/strings.xml
* And the needle:
* res
* Returns:
* res/research/handwriting/res
* </pre>
*/
static PathFragment trimTo(PathFragment haystack, PathFragment needle) {
if (needle.equals(PathFragment.EMPTY_FRAGMENT)) {
return haystack;
}
// Compute the overlap offset for duplicated parts of the needle.
int[] overlap = new int[needle.segmentCount() + 1];
// Start overlap at -1, as it will cancel out the increment in the search.
// See http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm for the
// details.
overlap[0] = -1;
for (int i = 0, j = -1; i < needle.segmentCount(); j++, i++, overlap[i] = j) {
while (j >= 0 && !needle.getSegment(i).equals(needle.getSegment(j))) {
// Walk the overlap until the bound is found.
j = overlap[j];
}
}
// TODO(corysmith): reverse the search algorithm.
// Keep the index of the found so that the rightmost index is taken.
int found = -1;
for (int i = 0, j = 0; i < haystack.segmentCount(); i++) {
while (j >= 0 && !haystack.getSegment(i).equals(needle.getSegment(j))) {
// Not matching, walk the needle index to attempt another match.
j = overlap[j];
}
j++;
// Needle index is exhausted, so the needle must match.
if (j == needle.segmentCount()) {
// Record the found index + 1 to be inclusive of the end index.
found = i + 1;
// Subtract one from the needle index to restart the search process
j = j - 1;
}
}
if (found != -1) {
// Return the subsection of the haystack.
return haystack.subFragment(0, found);
}
throw new IllegalArgumentException(String.format("%s was not found in %s", needle, haystack));
}
public static NestedSetBuilder<Artifact> collectTransitiveNativeLibsZips(
RuleContext ruleContext) {
NestedSetBuilder<Artifact> transitiveAarNativeLibs = NestedSetBuilder.naiveLinkOrder();
Iterable<NativeLibsZipsProvider> providers = getTransitivePrerequisites(
ruleContext, Mode.TARGET, NativeLibsZipsProvider.class);
for (NativeLibsZipsProvider nativeLibsZipsProvider : providers) {
transitiveAarNativeLibs.addTransitive(nativeLibsZipsProvider.getAarNativeLibs());
}
return transitiveAarNativeLibs;
}
Artifact compileDexWithJack(
MultidexMode mode, Optional<Artifact> mainDexList, Collection<Artifact> proguardSpecs) {
return jackCompilationHelper.compileAsDex(mode, mainDexList, proguardSpecs);
}
private void compileResources(
JavaSemantics javaSemantics,
ResourceApk resourceApk,
Artifact resourcesJar,
JavaCompilationArtifacts.Builder artifactsBuilder,
JavaTargetAttributes.Builder attributes,
NestedSetBuilder<Artifact> filesBuilder,
NestedSetBuilder<Artifact> jarsProducedForRuntime,
boolean useRClassGenerator) throws InterruptedException {
compileResourceJar(javaSemantics, resourceApk, resourcesJar, useRClassGenerator);
// Add the compiled resource jar to the classpath of the main compilation.
attributes.addDirectJars(NestedSetBuilder.create(Order.STABLE_ORDER, resourceClassJar));
// Add the compiled resource jar to the classpath of consuming targets.
// We don't actually use the ijar. That is almost the same as the resource class jar
// except for <clinit>, but it takes time to build and waiting for that to build would
// just delay building the rest of the library.
artifactsBuilder.addCompileTimeJar(resourceClassJar);
// Combined resource constants needs to come even before our own classes that may contain
// local resource constants.
artifactsBuilder.addRuntimeJar(resourceClassJar);
jarsProducedForRuntime.add(resourceClassJar);
// Add the compiled resource jar as a declared output of the rule.
filesBuilder.add(resourceSourceJar);
filesBuilder.add(resourceClassJar);
}
private void compileResourceJar(
JavaSemantics javaSemantics, ResourceApk resourceApk, Artifact resourcesJar,
boolean useRClassGenerator)
throws InterruptedException {
resourceSourceJar = ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.ANDROID_RESOURCES_SOURCE_JAR);
resourceClassJar = ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR);
JavaCompilationArtifacts.Builder javaArtifactsBuilder = new JavaCompilationArtifacts.Builder();
JavaTargetAttributes.Builder javacAttributes = new JavaTargetAttributes.Builder(javaSemantics)
.addSourceJar(resourcesJar);
JavaCompilationHelper javacHelper = new JavaCompilationHelper(
ruleContext, javaSemantics, getJavacOpts(), javacAttributes);
// Only build the class jar if it's not already generated internally by resource processing.
if (resourceApk.getResourceJavaClassJar() == null) {
if (useRClassGenerator) {
RClassGeneratorActionBuilder actionBuilder =
new RClassGeneratorActionBuilder(ruleContext)
.withPrimary(resourceApk.getPrimaryResource())
.withDependencies(resourceApk.getResourceDependencies())
.setClassJarOut(resourceClassJar);
actionBuilder.build();
} else {
Artifact outputDepsProto =
javacHelper.createOutputDepsProtoArtifact(resourceClassJar, javaArtifactsBuilder);
javacHelper.createCompileActionWithInstrumentation(
resourceClassJar,
null /* manifestProtoOutput */,
null /* genSourceJar */,
outputDepsProto,
javaArtifactsBuilder);
}
} else {
// Otherwise, it should have been the AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR.
Preconditions.checkArgument(
resourceApk.getResourceJavaClassJar().equals(
ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR)));
}
javacHelper.createSourceJarAction(resourceSourceJar, null);
}
private void createJarJarActions(
JavaTargetAttributes.Builder attributes,
NestedSetBuilder<Artifact> jarsProducedForRuntime,
Iterable<ResourceContainer> resourceContainers,
String originalPackage,
Artifact binaryResourcesJar) {
// Now use jarjar for the rest of the resources. We need to make a copy
// of the final generated resources for each of the targets included in
// the transitive closure of this binary.
for (ResourceContainer otherContainer : resourceContainers) {
if (otherContainer.getLabel().equals(ruleContext.getLabel())) {
continue;
}
Artifact resourcesJar = createResourceJarArtifact(ruleContext, otherContainer, ".jar");
// combined resource constants copy needs to come before library classes that may contain
// their local resource constants
attributes.addRuntimeClassPathEntry(resourcesJar);
Artifact jarJarRuleFile = createResourceJarArtifact(
ruleContext, otherContainer, ".jar_jarjar_rules.txt");
String jarJarRule = String.format("rule %s.* %s.@1",
originalPackage, otherContainer.getJavaPackage());
ruleContext.registerAction(new FileWriteAction(
ruleContext.getActionOwner(), jarJarRuleFile, jarJarRule, false));
FilesToRunProvider jarjar =
ruleContext.getExecutablePrerequisite("$jarjar_bin", Mode.HOST);
ruleContext.registerAction(new SpawnAction.Builder()
.setExecutable(jarjar)
.addArgument("process")
.addInputArgument(jarJarRuleFile)
.addInputArgument(binaryResourcesJar)
.addOutputArgument(resourcesJar)
.setProgressMessage("Repackaging jar")
.setMnemonic("AndroidRepackageJar")
.build(ruleContext));
jarsProducedForRuntime.add(resourcesJar);
}
}
private static Artifact createResourceJarArtifact(RuleContext ruleContext,
ResourceContainer container, String fileNameSuffix) {
String artifactName = container.getLabel().getName() + fileNameSuffix;
// Since the Java sources are generated by combining all resources with the
// ones included in the binary, the path of the artifact has to be unique
// per binary and per library (not only per library).
Artifact artifact = ruleContext.getUniqueDirectoryArtifact("resource_jars",
container.getLabel().getPackageIdentifier().getSourceRoot().getRelative(artifactName),
ruleContext.getBinOrGenfilesDirectory());
return artifact;
}
public JavaTargetAttributes init(
JavaSemantics javaSemantics,
AndroidSemantics androidSemantics,
ResourceApk resourceApk,
boolean addCoverageSupport,
boolean collectJavaCompilationArgs,
boolean isBinary)
throws InterruptedException {
classJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_CLASS_JAR);
idlHelper = new AndroidIdlHelper(ruleContext, classJar);
ImmutableList<Artifact> bootclasspath;
if (getAndroidConfig(ruleContext).desugarJava8()) {
bootclasspath = ImmutableList.<Artifact>builder()
.addAll(ruleContext.getPrerequisite("$desugar_java8_extra_bootclasspath", Mode.HOST)
.getProvider(FileProvider.class)
.getFilesToBuild())
.add(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar())
.build();
} else {
bootclasspath =
ImmutableList.of(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar());
}
JavaTargetAttributes.Builder attributes =
javaCommon
.initCommon(
idlHelper.getIdlGeneratedJavaSources(),
androidSemantics.getJavacArguments(ruleContext))
.setBootClassPath(bootclasspath);
JavaCompilationArtifacts.Builder artifactsBuilder = new JavaCompilationArtifacts.Builder();
NestedSetBuilder<Artifact> jarsProducedForRuntime = NestedSetBuilder.<Artifact>stableOrder();
NestedSetBuilder<Artifact> filesBuilder = NestedSetBuilder.<Artifact>stableOrder();
Artifact resourcesJar = resourceApk.getResourceJavaSrcJar();
if (resourcesJar != null) {
filesBuilder.add(resourcesJar);
// Use a fast-path R class generator for android_binary with local resources, where there is
// a bottleneck. For legacy resources, the srcjar and R class compiler don't match up
// (the legacy srcjar requires the createJarJar step below).
boolean useRClassGenerator =
getAndroidConfig(ruleContext).useRClassGenerator()
&& isBinary && !resourceApk.isLegacy();
compileResources(javaSemantics, resourceApk, resourcesJar, artifactsBuilder, attributes,
filesBuilder, jarsProducedForRuntime, useRClassGenerator);
if (resourceApk.isLegacy()) {
// Repackages the R.java for each dependency package and places the resultant jars before
// the dependency libraries to ensure that the generated resource ids are correct.
createJarJarActions(attributes, jarsProducedForRuntime,
resourceApk.getResourceDependencies().getResources(),
resourceApk.getPrimaryResource().getJavaPackage(), resourceClassJar);
}
}
JavaCompilationHelper helper = initAttributes(attributes, javaSemantics);
if (ruleContext.hasErrors()) {
return null;
}
if (addCoverageSupport) {
androidSemantics.addCoverageSupport(ruleContext, this, javaSemantics, true,
attributes, artifactsBuilder);
if (ruleContext.hasErrors()) {
return null;
}
}
jackCompilationHelper = initJack(helper.getAttributes());
if (ruleContext.hasErrors()) {
return null;
}
initJava(
javaSemantics,
helper,
artifactsBuilder,
collectJavaCompilationArgs,
filesBuilder,
isBinary);
if (ruleContext.hasErrors()) {
return null;
}
this.jarsProducedForRuntime = jarsProducedForRuntime.add(classJar).build();
return helper.getAttributes();
}
private JavaCompilationHelper initAttributes(
JavaTargetAttributes.Builder attributes, JavaSemantics semantics) {
JavaCompilationHelper helper = new JavaCompilationHelper(
ruleContext, semantics, javaCommon.getJavacOpts(), attributes);
helper.addLibrariesToAttributes(javaCommon.targetsTreatedAsDeps(ClasspathType.COMPILE_ONLY));
attributes.setRuleKind(ruleContext.getRule().getRuleClass());
attributes.setTargetLabel(ruleContext.getLabel());
JavaCommon.validateConstraint(ruleContext, "android",
javaCommon.targetsTreatedAsDeps(ClasspathType.BOTH));
ruleContext.checkSrcsSamePackage(true);
return helper;
}
JackCompilationHelper initJack(JavaTargetAttributes attributes) throws InterruptedException {
AndroidSdkProvider sdk = AndroidSdkProvider.fromRuleContext(ruleContext);
return new JackCompilationHelper.Builder()
// blaze infrastructure
.setRuleContext(ruleContext)
// configuration
.setOutputArtifact(
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_JACK_FILE))
// tools
.setJackBinary(sdk.getJack())
.setJillBinary(sdk.getJill())
.setResourceExtractorBinary(sdk.getResourceExtractor())
.setJackBaseClasspath(sdk.getAndroidBaseClasspathForJack())
// sources
.addJavaSources(attributes.getSourceFiles())
.addSourceJars(attributes.getSourceJars())
.addResources(attributes.getResources())
.addProcessorNames(attributes.getProcessorNames())
.addProcessorClasspathJars(attributes.getProcessorPath())
.addExports(JavaCommon.getExports(ruleContext))
.addClasspathDeps(javaCommon.targetsTreatedAsDeps(ClasspathType.COMPILE_ONLY))
.addRuntimeDeps(javaCommon.targetsTreatedAsDeps(ClasspathType.RUNTIME_ONLY))
.build();
}
private void initJava(
JavaSemantics javaSemantics,
JavaCompilationHelper helper,
JavaCompilationArtifacts.Builder javaArtifactsBuilder,
boolean collectJavaCompilationArgs,
NestedSetBuilder<Artifact> filesBuilder,
boolean isBinary)
throws InterruptedException {
JavaTargetAttributes attributes = helper.getAttributes();
if (ruleContext.hasErrors()) {
// Avoid leaving filesToBuild set to null, otherwise we'll get a NullPointerException masking
// the real error.
filesToBuild = filesBuilder.build();
return;
}
Artifact jar = null;
if (attributes.hasSourceFiles() || attributes.hasSourceJars() || attributes.hasResources()) {
// We only want to add a jar to the classpath of a dependent rule if it has content.
javaArtifactsBuilder.addRuntimeJar(classJar);
jar = classJar;
}
filesBuilder.add(classJar);
manifestProtoOutput = helper.createManifestProtoOutput(classJar);
// The gensrc jar is created only if the target uses annotation processing. Otherwise,
// it is null, and the source jar action will not depend on the compile action.
if (helper.usesAnnotationProcessing()) {
genClassJar = helper.createGenJar(classJar);
genSourceJar = helper.createGensrcJar(classJar);
helper.createGenJarAction(classJar, manifestProtoOutput, genClassJar);
}
srcJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_SOURCE_JAR);
javaSourceJarsProviderBuilder
.addSourceJar(srcJar)
.addAllTransitiveSourceJars(javaCommon.collectTransitiveSourceJars(srcJar));
helper.createSourceJarAction(srcJar, genSourceJar);
outputDepsProto = helper.createOutputDepsProtoArtifact(classJar, javaArtifactsBuilder);
helper.createCompileActionWithInstrumentation(classJar, manifestProtoOutput, genSourceJar,
outputDepsProto, javaArtifactsBuilder);
if (isBinary) {
generatedExtensionRegistryProvider =
javaSemantics.createGeneratedExtensionRegistry(
ruleContext,
javaCommon,
filesBuilder,
javaArtifactsBuilder,
javaRuleOutputJarsProviderBuilder,
javaSourceJarsProviderBuilder);
}
filesToBuild = filesBuilder.build();
if ((attributes.hasSourceFiles() || attributes.hasSourceJars()) && jar != null) {
iJar = helper.createCompileTimeJarAction(jar, javaArtifactsBuilder);
}
JavaCompilationArtifacts javaArtifacts = javaArtifactsBuilder.build();
compileTimeDependencyArtifacts =
javaCommon.collectCompileTimeDependencyArtifacts(
javaArtifacts.getCompileTimeDependencyArtifact());
javaCommon.setJavaCompilationArtifacts(javaArtifacts);
javaCommon.setClassPathFragment(
new ClasspathConfiguredFragment(
javaCommon.getJavaCompilationArtifacts(),
attributes,
asNeverLink,
helper.getBootclasspathOrDefault()));
transitiveNeverlinkLibraries = collectTransitiveNeverlinkLibraries(
ruleContext,
javaCommon.getDependencies(),
javaCommon.getJavaCompilationArtifacts().getRuntimeJars());
if (collectJavaCompilationArgs) {
boolean hasSources = attributes.hasSourceFiles() || attributes.hasSourceJars();
this.javaCompilationArgs =
collectJavaCompilationArgs(exportDeps, asNeverLink, hasSources);
this.recursiveJavaCompilationArgs = collectJavaCompilationArgs(
true, asNeverLink, /* hasSources */ true);
}
}
public RuleConfiguredTargetBuilder addTransitiveInfoProviders(
RuleConfiguredTargetBuilder builder,
AndroidSemantics androidSemantics,
Artifact aar,
ResourceApk resourceApk,
Artifact zipAlignedApk,
Iterable<Artifact> apksUnderTest) {
javaCommon.addTransitiveInfoProviders(builder, filesToBuild, classJar, ANDROID_COLLECTION_SPEC);
javaCommon.addGenJarsProvider(builder, genClassJar, genSourceJar);
idlHelper.addTransitiveInfoProviders(builder, classJar, manifestProtoOutput);
if (generatedExtensionRegistryProvider != null) {
builder.add(GeneratedExtensionRegistryProvider.class, generatedExtensionRegistryProvider);
}
OutputJar resourceJar = null;
if (resourceClassJar != null && resourceSourceJar != null) {
resourceJar = new OutputJar(resourceClassJar, null, resourceSourceJar);
javaRuleOutputJarsProviderBuilder.addOutputJar(resourceJar);
}
JavaSourceJarsProvider javaSourceJarsProvider = javaSourceJarsProviderBuilder.build();
return builder
.setFilesToBuild(filesToBuild)
.add(
JavaRuleOutputJarsProvider.class,
javaRuleOutputJarsProviderBuilder
.addOutputJar(classJar, iJar, srcJar)
.setJdeps(outputDepsProto)
.build())
.add(JavaSourceJarsProvider.class, javaSourceJarsProvider)
.add(
JavaRuntimeJarProvider.class,
new JavaRuntimeJarProvider(javaCommon.getJavaCompilationArtifacts().getRuntimeJars()))
.add(RunfilesProvider.class, RunfilesProvider.simple(getRunfiles()))
.add(AndroidResourcesProvider.class, resourceApk.toResourceProvider(ruleContext.getLabel()))
.add(
AndroidIdeInfoProvider.class,
createAndroidIdeInfoProvider(
ruleContext,
androidSemantics,
idlHelper,
resourceJar,
aar,
resourceApk,
zipAlignedApk,
apksUnderTest))
.add(
JavaCompilationArgsProvider.class,
JavaCompilationArgsProvider.create(
javaCompilationArgs,
recursiveJavaCompilationArgs,
compileTimeDependencyArtifacts,
NestedSetBuilder.<Artifact>emptySet(Order.STABLE_ORDER)))
.add(
JackLibraryProvider.class,
asNeverLink
? jackCompilationHelper.compileAsNeverlinkLibrary()
: jackCompilationHelper.compileAsLibrary())
.addSkylarkTransitiveInfo(AndroidSkylarkApiProvider.NAME, new AndroidSkylarkApiProvider())
.addOutputGroup(
OutputGroupProvider.HIDDEN_TOP_LEVEL, collectHiddenTopLevelArtifacts(ruleContext))
.addOutputGroup(
JavaSemantics.SOURCE_JARS_OUTPUT_GROUP,
javaSourceJarsProvider.getTransitiveSourceJars());
}
private Runfiles getRunfiles() {
// TODO(bazel-team): why return any Runfiles in the neverlink case?
if (asNeverLink) {
return new Runfiles.Builder(
ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles())
.addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES)
.build();
}
return JavaCommon.getRunfiles(
ruleContext, javaCommon.getJavaSemantics(), javaCommon.getJavaCompilationArtifacts(),
asNeverLink);
}
public static PathFragment getAssetDir(RuleContext ruleContext) {
return new PathFragment(ruleContext.attributes().get(
AndroidResourcesProvider.ResourceType.ASSETS.getAttribute() + "_dir",
Type.STRING));
}
public static NestedSet<LinkerInput> collectTransitiveNativeLibraries(
Iterable<? extends TransitiveInfoCollection> deps) {
NestedSetBuilder<LinkerInput> builder = NestedSetBuilder.stableOrder();
for (TransitiveInfoCollection dep : deps) {
AndroidNativeLibraryProvider android = dep.getProvider(AndroidNativeLibraryProvider.class);
if (android != null) {
builder.addTransitive(android.getTransitiveAndroidNativeLibraries());
continue;
}
JavaNativeLibraryProvider java = dep.getProvider(JavaNativeLibraryProvider.class);
if (java != null) {
builder.addTransitive(java.getTransitiveJavaNativeLibraries());
continue;
}
CcNativeLibraryProvider cc = dep.getProvider(CcNativeLibraryProvider.class);
if (cc != null) {
for (LinkerInput input : cc.getTransitiveCcNativeLibraries()) {
Artifact library = input.getOriginalLibraryArtifact();
String name = library.getFilename();
if (CppFileTypes.SHARED_LIBRARY.matches(name)
|| CppFileTypes.VERSIONED_SHARED_LIBRARY.matches(name)) {
builder.add(input);
}
}
continue;
}
}
return builder.build();
}
public static AndroidResourcesProvider getAndroidResources(RuleContext ruleContext) {
if (!ruleContext.attributes().has("resources", BuildType.LABEL)) {
return null;
}
TransitiveInfoCollection prerequisite = ruleContext.getPrerequisite("resources", Mode.TARGET);
if (prerequisite == null) {
return null;
}
ruleContext.ruleWarning(
"The use of the android_resources rule and the resources attribute is deprecated. "
+ "Please use the resource_files, assets, and manifest attributes of android_library.");
return prerequisite.getProvider(AndroidResourcesProvider.class);
}
/**
* Collects Java compilation arguments for this target.
*
* @param recursive Whether to scan dependencies recursively.
* @param isNeverLink Whether the target has the 'neverlink' attr.
* @param hasSrcs If false, deps are exported (deprecated behaviour)
*/
private JavaCompilationArgs collectJavaCompilationArgs(boolean recursive, boolean isNeverLink,
boolean hasSrcs) {
boolean exportDeps = !hasSrcs
&& ruleContext.getFragment(AndroidConfiguration.class).allowSrcsLessAndroidLibraryDeps();
return javaCommon.collectJavaCompilationArgs(recursive, isNeverLink, exportDeps);
}
public ImmutableList<String> getJavacOpts() {
return javaCommon.getJavacOpts();
}
public Artifact getGenClassJar() {
return genClassJar;
}
@Nullable public Artifact getGenSourceJar() {
return genSourceJar;
}
public ImmutableList<Artifact> getRuntimeJars() {
return javaCommon.getJavaCompilationArtifacts().getRuntimeJars();
}
public Artifact getResourceClassJar() {
return resourceClassJar;
}
/**
* Returns Jars produced by this rule that may go into the runtime classpath. By contrast
* {@link #getRuntimeJars()} returns the complete runtime classpath needed by this rule, including
* dependencies.
*/
public NestedSet<Artifact> getJarsProducedForRuntime() {
return jarsProducedForRuntime;
}
public Artifact getInstrumentedJar() {
return javaCommon.getJavaCompilationArtifacts().getInstrumentedJar();
}
public NestedSet<Artifact> getTransitiveNeverLinkLibraries() {
return transitiveNeverlinkLibraries;
}
public boolean isNeverLink() {
return asNeverLink;
}
public CcLinkParamsStore getCcLinkParamsStore() {
return getCcLinkParamsStore(
javaCommon.targetsTreatedAsDeps(ClasspathType.BOTH), ImmutableList.<String>of());
}
public static CcLinkParamsStore getCcLinkParamsStore(
final Iterable<? extends TransitiveInfoCollection> deps, final Collection<String> linkOpts) {
return new CcLinkParamsStore() {
@Override
protected void collect(
CcLinkParams.Builder builder, boolean linkingStatically, boolean linkShared) {
builder.addTransitiveTargets(
deps,
// Link in Java-specific C++ code in the transitive closure
JavaCcLinkParamsProvider.TO_LINK_PARAMS,
// Link in Android-specific C++ code (e.g., android_libraries) in the transitive closure
AndroidCcLinkParamsProvider.TO_LINK_PARAMS,
// Link in non-language-specific C++ code in the transitive closure
CcLinkParamsProvider.TO_LINK_PARAMS);
builder.addLinkOpts(linkOpts);
}
};
}
/**
* Returns {@link AndroidConfiguration} in given context.
*/
static AndroidConfiguration getAndroidConfig(RuleContext context) {
return context.getConfiguration().getFragment(AndroidConfiguration.class);
}
private NestedSet<Artifact> collectHiddenTopLevelArtifacts(RuleContext ruleContext) {
NestedSetBuilder<Artifact> builder = NestedSetBuilder.stableOrder();
for (OutputGroupProvider provider :
getTransitivePrerequisites(ruleContext, Mode.TARGET, OutputGroupProvider.class)) {
builder.addTransitive(provider.getOutputGroup(OutputGroupProvider.HIDDEN_TOP_LEVEL));
}
return builder.build();
}
}
| src/main/java/com/google/devtools/build/lib/rules/android/AndroidCommon.java | // Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.android;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ResourceSet;
import com.google.devtools.build.lib.analysis.AnalysisUtils;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.OutputGroupProvider;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.analysis.actions.FileWriteAction;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.collect.IterablesChain;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.packages.AggregatingAttributeMapper;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.rules.android.AndroidResourcesProvider.ResourceContainer;
import com.google.devtools.build.lib.rules.android.AndroidResourcesProvider.ResourceType;
import com.google.devtools.build.lib.rules.android.AndroidRuleClasses.MultidexMode;
import com.google.devtools.build.lib.rules.cpp.CcLinkParams;
import com.google.devtools.build.lib.rules.cpp.CcLinkParamsProvider;
import com.google.devtools.build.lib.rules.cpp.CcLinkParamsStore;
import com.google.devtools.build.lib.rules.cpp.CcNativeLibraryProvider;
import com.google.devtools.build.lib.rules.cpp.CppFileTypes;
import com.google.devtools.build.lib.rules.cpp.LinkerInput;
import com.google.devtools.build.lib.rules.java.ClasspathConfiguredFragment;
import com.google.devtools.build.lib.rules.java.JavaCcLinkParamsProvider;
import com.google.devtools.build.lib.rules.java.JavaCommon;
import com.google.devtools.build.lib.rules.java.JavaCompilationArgs;
import com.google.devtools.build.lib.rules.java.JavaCompilationArgs.ClasspathType;
import com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider;
import com.google.devtools.build.lib.rules.java.JavaCompilationArtifacts;
import com.google.devtools.build.lib.rules.java.JavaCompilationHelper;
import com.google.devtools.build.lib.rules.java.JavaNativeLibraryProvider;
import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider;
import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider.OutputJar;
import com.google.devtools.build.lib.rules.java.JavaRuntimeJarProvider;
import com.google.devtools.build.lib.rules.java.JavaSemantics;
import com.google.devtools.build.lib.rules.java.JavaSourceJarsProvider;
import com.google.devtools.build.lib.rules.java.JavaTargetAttributes;
import com.google.devtools.build.lib.rules.java.JavaUtil;
import com.google.devtools.build.lib.rules.java.proto.GeneratedExtensionRegistryProvider;
import com.google.devtools.build.lib.rules.test.InstrumentedFilesCollector.InstrumentationSpec;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A helper class for android rules.
*
* <p>Helps create the java compilation as well as handling the exporting of the java compilation
* artifacts to the other rules.
*/
public class AndroidCommon {
public static final InstrumentationSpec ANDROID_COLLECTION_SPEC = JavaCommon.JAVA_COLLECTION_SPEC
.withDependencyAttributes("deps", "data", "exports", "runtime_deps", "binary_under_test");
public static final Set<String> TRANSITIVE_ATTRIBUTES = ImmutableSet.of(
"deps",
"exports"
);
public static final <T extends TransitiveInfoProvider> Iterable<T> getTransitivePrerequisites(
RuleContext ruleContext, Mode mode, final Class<T> classType) {
IterablesChain.Builder<T> builder = IterablesChain.builder();
for (String attr : TRANSITIVE_ATTRIBUTES) {
if (ruleContext.getAttribute(attr) != null) {
builder.add(ruleContext.getPrerequisites(attr, mode, classType));
}
}
return builder.build();
}
public static final Iterable<TransitiveInfoCollection> collectTransitiveInfo(
RuleContext ruleContext, Mode mode) {
ImmutableList.Builder<TransitiveInfoCollection> builder = ImmutableList.builder();
for (String attr : TRANSITIVE_ATTRIBUTES) {
if (ruleContext.getAttribute(attr) != null) {
builder.addAll(ruleContext.getPrerequisites(attr, mode));
}
}
return builder.build();
}
private final RuleContext ruleContext;
private final JavaCommon javaCommon;
private final boolean asNeverLink;
private final boolean exportDeps;
private NestedSet<Artifact> compileTimeDependencyArtifacts;
private NestedSet<Artifact> filesToBuild;
private NestedSet<Artifact> transitiveNeverlinkLibraries =
NestedSetBuilder.emptySet(Order.STABLE_ORDER);
private JavaCompilationArgs javaCompilationArgs = JavaCompilationArgs.EMPTY_ARGS;
private JavaCompilationArgs recursiveJavaCompilationArgs = JavaCompilationArgs.EMPTY_ARGS;
private JackCompilationHelper jackCompilationHelper;
private ImmutableList<Artifact> jarsProducedForRuntime;
private Artifact classJar;
private Artifact iJar;
private Artifact srcJar;
private Artifact genClassJar;
private Artifact genSourceJar;
private Artifact resourceClassJar;
private Artifact resourceSourceJar;
private Artifact outputDepsProto;
private GeneratedExtensionRegistryProvider generatedExtensionRegistryProvider;
private final JavaSourceJarsProvider.Builder javaSourceJarsProviderBuilder =
JavaSourceJarsProvider.builder();
private final JavaRuleOutputJarsProvider.Builder javaRuleOutputJarsProviderBuilder =
JavaRuleOutputJarsProvider.builder();
private Artifact manifestProtoOutput;
private AndroidIdlHelper idlHelper;
public AndroidCommon(JavaCommon javaCommon) {
this(javaCommon, JavaCommon.isNeverLink(javaCommon.getRuleContext()), false);
}
/**
* Creates a new AndroidCommon.
* @param common the JavaCommon instance
* @param asNeverLink Boolean to indicate if this rule should be treated as a compile time dep
* by consuming rules.
* @param exportDeps Boolean to indicate if the dependencies should be treated as "exported" deps.
*/
public AndroidCommon(JavaCommon common, boolean asNeverLink, boolean exportDeps) {
this.ruleContext = common.getRuleContext();
this.asNeverLink = asNeverLink;
this.exportDeps = exportDeps;
this.javaCommon = common;
}
/**
* Collects the transitive neverlink dependencies.
*
* @param ruleContext the context of the rule neverlink deps are to be computed for
* @param deps the targets to be treated as dependencies
* @param runtimeJars the runtime jars produced by the rule (non-transitive)
*
* @return a nested set of the neverlink deps.
*/
public static NestedSet<Artifact> collectTransitiveNeverlinkLibraries(
RuleContext ruleContext, Iterable<? extends TransitiveInfoCollection> deps,
ImmutableList<Artifact> runtimeJars) {
NestedSetBuilder<Artifact> builder = NestedSetBuilder.naiveLinkOrder();
for (AndroidNeverLinkLibrariesProvider provider : AnalysisUtils.getProviders(deps,
AndroidNeverLinkLibrariesProvider.class)) {
builder.addTransitive(provider.getTransitiveNeverLinkLibraries());
}
if (JavaCommon.isNeverLink(ruleContext)) {
builder.addAll(runtimeJars);
for (JavaCompilationArgsProvider provider : AnalysisUtils.getProviders(
deps, JavaCompilationArgsProvider.class)) {
builder.addTransitive(provider.getRecursiveJavaCompilationArgs().getRuntimeJars());
}
}
return builder.build();
}
/**
* Creates an action that converts {@code jarToDex} to a dex file. The output will be stored in
* the {@link com.google.devtools.build.lib.actions.Artifact} {@code dxJar}.
*/
public static void createDexAction(
RuleContext ruleContext,
Artifact jarToDex, Artifact classesDex, List<String> dexOptions, boolean multidex,
Artifact mainDexList) {
List<String> args = new ArrayList<>();
args.add("--dex");
// Add --no-locals to coverage builds. Older coverage tools don't correctly preserve local
// variable information in stack frame maps that are required since Java 7, so to avoid runtime
// errors we just don't add local variable info in the first place. This may no longer be
// necessary, however, as long as we use a coverage tool that generates stack frame maps.
if (ruleContext.getConfiguration().isCodeCoverageEnabled()) {
args.add("--no-locals"); // TODO(bazel-team): Is this still needed?
}
// Multithreaded dex does not work when using --multi-dex.
if (!multidex) {
// Multithreaded dex tends to run faster, but only up to about 5 threads (at which point the
// law of diminishing returns kicks in). This was determined experimentally, with 5-thread dex
// performing about 25% faster than 1-thread dex.
args.add("--num-threads=5");
}
args.addAll(dexOptions);
if (multidex) {
args.add("--multi-dex");
if (mainDexList != null) {
args.add("--main-dex-list=" + mainDexList.getExecPathString());
}
}
args.add("--output=" + classesDex.getExecPathString());
args.add(jarToDex.getExecPathString());
SpawnAction.Builder builder = new SpawnAction.Builder()
.setExecutable(AndroidSdkProvider.fromRuleContext(ruleContext).getDx())
.addInput(jarToDex)
.addOutput(classesDex)
.addArguments(args)
.setProgressMessage("Converting " + jarToDex.getExecPathString() + " to dex format")
.setMnemonic("AndroidDexer")
.setResources(ResourceSet.createWithRamCpuIo(4096.0, 5.0, 0.0));
if (mainDexList != null) {
builder.addInput(mainDexList);
}
ruleContext.registerAction(builder.build(ruleContext));
}
public static AndroidIdeInfoProvider createAndroidIdeInfoProvider(
RuleContext ruleContext,
AndroidSemantics semantics,
AndroidIdlHelper idlHelper,
OutputJar resourceJar,
Artifact aar,
ResourceApk resourceApk,
Artifact zipAlignedApk,
Iterable<Artifact> apksUnderTest) {
AndroidIdeInfoProvider.Builder ideInfoProviderBuilder =
new AndroidIdeInfoProvider.Builder()
.setIdlClassJar(idlHelper.getIdlClassJar())
.setIdlSourceJar(idlHelper.getIdlSourceJar())
.setResourceJar(resourceJar)
.setAar(aar)
.addIdlImportRoot(idlHelper.getIdlImportRoot())
.addIdlParcelables(idlHelper.getIdlParcelables())
.addIdlSrcs(idlHelper.getIdlSources())
.addIdlGeneratedJavaFiles(idlHelper.getIdlGeneratedJavaSources())
.addAllApksUnderTest(apksUnderTest);
if (zipAlignedApk != null) {
ideInfoProviderBuilder.setApk(zipAlignedApk);
}
// If the rule defines resources, put those in the IDE info. Otherwise, proxy the data coming
// from the android_resources rule in its direct dependencies, if such a thing exists.
if (LocalResourceContainer.definesAndroidResources(ruleContext.attributes())) {
ideInfoProviderBuilder
.setDefinesAndroidResources(true)
.addResourceSources(resourceApk.getPrimaryResource().getArtifacts(ResourceType.RESOURCES))
.addAssetSources(
resourceApk.getPrimaryResource().getArtifacts(ResourceType.ASSETS),
getAssetDir(ruleContext))
// Sets the possibly merged manifest and the raw manifest.
.setGeneratedManifest(resourceApk.getPrimaryResource().getManifest())
.setManifest(ruleContext.getPrerequisiteArtifact("manifest", Mode.TARGET))
.setJavaPackage(getJavaPackage(ruleContext));
} else {
semantics.addNonLocalResources(ruleContext, resourceApk, ideInfoProviderBuilder);
}
return ideInfoProviderBuilder.build();
}
public static String getJavaPackage(RuleContext ruleContext) {
AttributeMap attributes = ruleContext.attributes();
if (attributes.isAttributeValueExplicitlySpecified("custom_package")) {
return attributes.get("custom_package", Type.STRING);
}
return getDefaultJavaPackage(ruleContext.getRule());
}
public static Iterable<String> getPossibleJavaPackages(Rule rule) {
AggregatingAttributeMapper attributes = AggregatingAttributeMapper.of(rule);
if (attributes.isAttributeValueExplicitlySpecified("custom_package")) {
return attributes.visitAttribute("custom_package", Type.STRING);
}
return ImmutableList.of(getDefaultJavaPackage(rule));
}
private static String getDefaultJavaPackage(Rule rule) {
PathFragment nameFragment = rule.getPackage().getNameFragment();
String packageName = JavaUtil.getJavaFullClassname(nameFragment);
if (packageName != null) {
return packageName;
} else {
// This is a workaround for libraries that don't follow the standard Bazel package format
return nameFragment.getPathString().replace('/', '.');
}
}
static PathFragment getSourceDirectoryRelativePathFromResource(Artifact resource) {
PathFragment resourceDir = LocalResourceContainer.Builder.findResourceDir(resource);
if (resourceDir == null) {
return null;
}
return trimTo(resource.getRootRelativePath(), resourceDir);
}
/**
* Finds the rightmost occurrence of the needle and returns subfragment of the haystack from
* left to the end of the occurrence inclusive of the needle.
*
* <pre>
* `Example:
* Given the haystack:
* res/research/handwriting/res/values/strings.xml
* And the needle:
* res
* Returns:
* res/research/handwriting/res
* </pre>
*/
static PathFragment trimTo(PathFragment haystack, PathFragment needle) {
if (needle.equals(PathFragment.EMPTY_FRAGMENT)) {
return haystack;
}
// Compute the overlap offset for duplicated parts of the needle.
int[] overlap = new int[needle.segmentCount() + 1];
// Start overlap at -1, as it will cancel out the increment in the search.
// See http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm for the
// details.
overlap[0] = -1;
for (int i = 0, j = -1; i < needle.segmentCount(); j++, i++, overlap[i] = j) {
while (j >= 0 && !needle.getSegment(i).equals(needle.getSegment(j))) {
// Walk the overlap until the bound is found.
j = overlap[j];
}
}
// TODO(corysmith): reverse the search algorithm.
// Keep the index of the found so that the rightmost index is taken.
int found = -1;
for (int i = 0, j = 0; i < haystack.segmentCount(); i++) {
while (j >= 0 && !haystack.getSegment(i).equals(needle.getSegment(j))) {
// Not matching, walk the needle index to attempt another match.
j = overlap[j];
}
j++;
// Needle index is exhausted, so the needle must match.
if (j == needle.segmentCount()) {
// Record the found index + 1 to be inclusive of the end index.
found = i + 1;
// Subtract one from the needle index to restart the search process
j = j - 1;
}
}
if (found != -1) {
// Return the subsection of the haystack.
return haystack.subFragment(0, found);
}
throw new IllegalArgumentException(String.format("%s was not found in %s", needle, haystack));
}
public static NestedSetBuilder<Artifact> collectTransitiveNativeLibsZips(
RuleContext ruleContext) {
NestedSetBuilder<Artifact> transitiveAarNativeLibs = NestedSetBuilder.naiveLinkOrder();
Iterable<NativeLibsZipsProvider> providers = getTransitivePrerequisites(
ruleContext, Mode.TARGET, NativeLibsZipsProvider.class);
for (NativeLibsZipsProvider nativeLibsZipsProvider : providers) {
transitiveAarNativeLibs.addTransitive(nativeLibsZipsProvider.getAarNativeLibs());
}
return transitiveAarNativeLibs;
}
Artifact compileDexWithJack(
MultidexMode mode, Optional<Artifact> mainDexList, Collection<Artifact> proguardSpecs) {
return jackCompilationHelper.compileAsDex(mode, mainDexList, proguardSpecs);
}
private void compileResources(
JavaSemantics javaSemantics,
ResourceApk resourceApk,
Artifact resourcesJar,
JavaCompilationArtifacts.Builder artifactsBuilder,
JavaTargetAttributes.Builder attributes,
NestedSetBuilder<Artifact> filesBuilder,
ImmutableList.Builder<Artifact> jarsProducedForRuntime,
boolean useRClassGenerator) throws InterruptedException {
compileResourceJar(javaSemantics, resourceApk, resourcesJar, useRClassGenerator);
// Add the compiled resource jar to the classpath of the main compilation.
attributes.addDirectJars(NestedSetBuilder.create(Order.STABLE_ORDER, resourceClassJar));
// Add the compiled resource jar to the classpath of consuming targets.
// We don't actually use the ijar. That is almost the same as the resource class jar
// except for <clinit>, but it takes time to build and waiting for that to build would
// just delay building the rest of the library.
artifactsBuilder.addCompileTimeJar(resourceClassJar);
// Combined resource constants needs to come even before our own classes that may contain
// local resource constants.
artifactsBuilder.addRuntimeJar(resourceClassJar);
jarsProducedForRuntime.add(resourceClassJar);
// Add the compiled resource jar as a declared output of the rule.
filesBuilder.add(resourceSourceJar);
filesBuilder.add(resourceClassJar);
}
private void compileResourceJar(
JavaSemantics javaSemantics, ResourceApk resourceApk, Artifact resourcesJar,
boolean useRClassGenerator)
throws InterruptedException {
resourceSourceJar = ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.ANDROID_RESOURCES_SOURCE_JAR);
resourceClassJar = ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR);
JavaCompilationArtifacts.Builder javaArtifactsBuilder = new JavaCompilationArtifacts.Builder();
JavaTargetAttributes.Builder javacAttributes = new JavaTargetAttributes.Builder(javaSemantics)
.addSourceJar(resourcesJar);
JavaCompilationHelper javacHelper = new JavaCompilationHelper(
ruleContext, javaSemantics, getJavacOpts(), javacAttributes);
// Only build the class jar if it's not already generated internally by resource processing.
if (resourceApk.getResourceJavaClassJar() == null) {
if (useRClassGenerator) {
RClassGeneratorActionBuilder actionBuilder =
new RClassGeneratorActionBuilder(ruleContext)
.withPrimary(resourceApk.getPrimaryResource())
.withDependencies(resourceApk.getResourceDependencies())
.setClassJarOut(resourceClassJar);
actionBuilder.build();
} else {
Artifact outputDepsProto =
javacHelper.createOutputDepsProtoArtifact(resourceClassJar, javaArtifactsBuilder);
javacHelper.createCompileActionWithInstrumentation(
resourceClassJar,
null /* manifestProtoOutput */,
null /* genSourceJar */,
outputDepsProto,
javaArtifactsBuilder);
}
} else {
// Otherwise, it should have been the AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR.
Preconditions.checkArgument(
resourceApk.getResourceJavaClassJar().equals(
ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR)));
}
javacHelper.createSourceJarAction(resourceSourceJar, null);
}
private void createJarJarActions(
JavaTargetAttributes.Builder attributes,
ImmutableList.Builder<Artifact> jarsProducedForRuntime,
Iterable<ResourceContainer> resourceContainers,
String originalPackage,
Artifact binaryResourcesJar) {
// Now use jarjar for the rest of the resources. We need to make a copy
// of the final generated resources for each of the targets included in
// the transitive closure of this binary.
for (ResourceContainer otherContainer : resourceContainers) {
if (otherContainer.getLabel().equals(ruleContext.getLabel())) {
continue;
}
Artifact resourcesJar = createResourceJarArtifact(ruleContext, otherContainer, ".jar");
// combined resource constants copy needs to come before library classes that may contain
// their local resource constants
attributes.addRuntimeClassPathEntry(resourcesJar);
Artifact jarJarRuleFile = createResourceJarArtifact(
ruleContext, otherContainer, ".jar_jarjar_rules.txt");
String jarJarRule = String.format("rule %s.* %s.@1",
originalPackage, otherContainer.getJavaPackage());
ruleContext.registerAction(new FileWriteAction(
ruleContext.getActionOwner(), jarJarRuleFile, jarJarRule, false));
FilesToRunProvider jarjar =
ruleContext.getExecutablePrerequisite("$jarjar_bin", Mode.HOST);
ruleContext.registerAction(new SpawnAction.Builder()
.setExecutable(jarjar)
.addArgument("process")
.addInputArgument(jarJarRuleFile)
.addInputArgument(binaryResourcesJar)
.addOutputArgument(resourcesJar)
.setProgressMessage("Repackaging jar")
.setMnemonic("AndroidRepackageJar")
.build(ruleContext));
jarsProducedForRuntime.add(resourcesJar);
}
}
private static Artifact createResourceJarArtifact(RuleContext ruleContext,
ResourceContainer container, String fileNameSuffix) {
String artifactName = container.getLabel().getName() + fileNameSuffix;
// Since the Java sources are generated by combining all resources with the
// ones included in the binary, the path of the artifact has to be unique
// per binary and per library (not only per library).
Artifact artifact = ruleContext.getUniqueDirectoryArtifact("resource_jars",
container.getLabel().getPackageIdentifier().getSourceRoot().getRelative(artifactName),
ruleContext.getBinOrGenfilesDirectory());
return artifact;
}
public JavaTargetAttributes init(
JavaSemantics javaSemantics,
AndroidSemantics androidSemantics,
ResourceApk resourceApk,
boolean addCoverageSupport,
boolean collectJavaCompilationArgs,
boolean isBinary)
throws InterruptedException {
classJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_CLASS_JAR);
idlHelper = new AndroidIdlHelper(ruleContext, classJar);
ImmutableList<Artifact> bootclasspath;
if (getAndroidConfig(ruleContext).desugarJava8()) {
bootclasspath = ImmutableList.<Artifact>builder()
.addAll(ruleContext.getPrerequisite("$desugar_java8_extra_bootclasspath", Mode.HOST)
.getProvider(FileProvider.class)
.getFilesToBuild())
.add(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar())
.build();
} else {
bootclasspath =
ImmutableList.of(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar());
}
JavaTargetAttributes.Builder attributes =
javaCommon
.initCommon(
idlHelper.getIdlGeneratedJavaSources(),
androidSemantics.getJavacArguments(ruleContext))
.setBootClassPath(bootclasspath);
JavaCompilationArtifacts.Builder artifactsBuilder = new JavaCompilationArtifacts.Builder();
ImmutableList.Builder<Artifact> jarsProducedForRuntime = ImmutableList.builder();
NestedSetBuilder<Artifact> filesBuilder = NestedSetBuilder.<Artifact>stableOrder();
Artifact resourcesJar = resourceApk.getResourceJavaSrcJar();
if (resourcesJar != null) {
filesBuilder.add(resourcesJar);
// Use a fast-path R class generator for android_binary with local resources, where there is
// a bottleneck. For legacy resources, the srcjar and R class compiler don't match up
// (the legacy srcjar requires the createJarJar step below).
boolean useRClassGenerator =
getAndroidConfig(ruleContext).useRClassGenerator()
&& isBinary && !resourceApk.isLegacy();
compileResources(javaSemantics, resourceApk, resourcesJar, artifactsBuilder, attributes,
filesBuilder, jarsProducedForRuntime, useRClassGenerator);
if (resourceApk.isLegacy()) {
// Repackages the R.java for each dependency package and places the resultant jars before
// the dependency libraries to ensure that the generated resource ids are correct.
createJarJarActions(attributes, jarsProducedForRuntime,
resourceApk.getResourceDependencies().getResources(),
resourceApk.getPrimaryResource().getJavaPackage(), resourceClassJar);
}
}
JavaCompilationHelper helper = initAttributes(attributes, javaSemantics);
if (ruleContext.hasErrors()) {
return null;
}
if (addCoverageSupport) {
androidSemantics.addCoverageSupport(ruleContext, this, javaSemantics, true,
attributes, artifactsBuilder);
if (ruleContext.hasErrors()) {
return null;
}
}
jackCompilationHelper = initJack(helper.getAttributes());
if (ruleContext.hasErrors()) {
return null;
}
initJava(
javaSemantics,
helper,
artifactsBuilder,
collectJavaCompilationArgs,
filesBuilder,
isBinary);
if (ruleContext.hasErrors()) {
return null;
}
this.jarsProducedForRuntime = jarsProducedForRuntime.add(classJar).build();
return helper.getAttributes();
}
private JavaCompilationHelper initAttributes(
JavaTargetAttributes.Builder attributes, JavaSemantics semantics) {
JavaCompilationHelper helper = new JavaCompilationHelper(
ruleContext, semantics, javaCommon.getJavacOpts(), attributes);
helper.addLibrariesToAttributes(javaCommon.targetsTreatedAsDeps(ClasspathType.COMPILE_ONLY));
attributes.setRuleKind(ruleContext.getRule().getRuleClass());
attributes.setTargetLabel(ruleContext.getLabel());
JavaCommon.validateConstraint(ruleContext, "android",
javaCommon.targetsTreatedAsDeps(ClasspathType.BOTH));
ruleContext.checkSrcsSamePackage(true);
return helper;
}
JackCompilationHelper initJack(JavaTargetAttributes attributes) throws InterruptedException {
AndroidSdkProvider sdk = AndroidSdkProvider.fromRuleContext(ruleContext);
return new JackCompilationHelper.Builder()
// blaze infrastructure
.setRuleContext(ruleContext)
// configuration
.setOutputArtifact(
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_JACK_FILE))
// tools
.setJackBinary(sdk.getJack())
.setJillBinary(sdk.getJill())
.setResourceExtractorBinary(sdk.getResourceExtractor())
.setJackBaseClasspath(sdk.getAndroidBaseClasspathForJack())
// sources
.addJavaSources(attributes.getSourceFiles())
.addSourceJars(attributes.getSourceJars())
.addResources(attributes.getResources())
.addProcessorNames(attributes.getProcessorNames())
.addProcessorClasspathJars(attributes.getProcessorPath())
.addExports(JavaCommon.getExports(ruleContext))
.addClasspathDeps(javaCommon.targetsTreatedAsDeps(ClasspathType.COMPILE_ONLY))
.addRuntimeDeps(javaCommon.targetsTreatedAsDeps(ClasspathType.RUNTIME_ONLY))
.build();
}
private void initJava(
JavaSemantics javaSemantics,
JavaCompilationHelper helper,
JavaCompilationArtifacts.Builder javaArtifactsBuilder,
boolean collectJavaCompilationArgs,
NestedSetBuilder<Artifact> filesBuilder,
boolean isBinary)
throws InterruptedException {
JavaTargetAttributes attributes = helper.getAttributes();
if (ruleContext.hasErrors()) {
// Avoid leaving filesToBuild set to null, otherwise we'll get a NullPointerException masking
// the real error.
filesToBuild = filesBuilder.build();
return;
}
Artifact jar = null;
if (attributes.hasSourceFiles() || attributes.hasSourceJars() || attributes.hasResources()) {
// We only want to add a jar to the classpath of a dependent rule if it has content.
javaArtifactsBuilder.addRuntimeJar(classJar);
jar = classJar;
}
filesBuilder.add(classJar);
manifestProtoOutput = helper.createManifestProtoOutput(classJar);
// The gensrc jar is created only if the target uses annotation processing. Otherwise,
// it is null, and the source jar action will not depend on the compile action.
if (helper.usesAnnotationProcessing()) {
genClassJar = helper.createGenJar(classJar);
genSourceJar = helper.createGensrcJar(classJar);
helper.createGenJarAction(classJar, manifestProtoOutput, genClassJar);
}
srcJar = ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_SOURCE_JAR);
javaSourceJarsProviderBuilder
.addSourceJar(srcJar)
.addAllTransitiveSourceJars(javaCommon.collectTransitiveSourceJars(srcJar));
helper.createSourceJarAction(srcJar, genSourceJar);
outputDepsProto = helper.createOutputDepsProtoArtifact(classJar, javaArtifactsBuilder);
helper.createCompileActionWithInstrumentation(classJar, manifestProtoOutput, genSourceJar,
outputDepsProto, javaArtifactsBuilder);
if (isBinary) {
generatedExtensionRegistryProvider =
javaSemantics.createGeneratedExtensionRegistry(
ruleContext,
javaCommon,
filesBuilder,
javaArtifactsBuilder,
javaRuleOutputJarsProviderBuilder,
javaSourceJarsProviderBuilder);
}
filesToBuild = filesBuilder.build();
if ((attributes.hasSourceFiles() || attributes.hasSourceJars()) && jar != null) {
iJar = helper.createCompileTimeJarAction(jar, javaArtifactsBuilder);
}
JavaCompilationArtifacts javaArtifacts = javaArtifactsBuilder.build();
compileTimeDependencyArtifacts =
javaCommon.collectCompileTimeDependencyArtifacts(
javaArtifacts.getCompileTimeDependencyArtifact());
javaCommon.setJavaCompilationArtifacts(javaArtifacts);
javaCommon.setClassPathFragment(
new ClasspathConfiguredFragment(
javaCommon.getJavaCompilationArtifacts(),
attributes,
asNeverLink,
helper.getBootclasspathOrDefault()));
transitiveNeverlinkLibraries = collectTransitiveNeverlinkLibraries(
ruleContext,
javaCommon.getDependencies(),
javaCommon.getJavaCompilationArtifacts().getRuntimeJars());
if (collectJavaCompilationArgs) {
boolean hasSources = attributes.hasSourceFiles() || attributes.hasSourceJars();
this.javaCompilationArgs =
collectJavaCompilationArgs(exportDeps, asNeverLink, hasSources);
this.recursiveJavaCompilationArgs = collectJavaCompilationArgs(
true, asNeverLink, /* hasSources */ true);
}
}
public RuleConfiguredTargetBuilder addTransitiveInfoProviders(
RuleConfiguredTargetBuilder builder,
AndroidSemantics androidSemantics,
Artifact aar,
ResourceApk resourceApk,
Artifact zipAlignedApk,
Iterable<Artifact> apksUnderTest) {
javaCommon.addTransitiveInfoProviders(builder, filesToBuild, classJar, ANDROID_COLLECTION_SPEC);
javaCommon.addGenJarsProvider(builder, genClassJar, genSourceJar);
idlHelper.addTransitiveInfoProviders(builder, classJar, manifestProtoOutput);
if (generatedExtensionRegistryProvider != null) {
builder.add(GeneratedExtensionRegistryProvider.class, generatedExtensionRegistryProvider);
}
OutputJar resourceJar = null;
if (resourceClassJar != null && resourceSourceJar != null) {
resourceJar = new OutputJar(resourceClassJar, null, resourceSourceJar);
javaRuleOutputJarsProviderBuilder.addOutputJar(resourceJar);
}
JavaSourceJarsProvider javaSourceJarsProvider = javaSourceJarsProviderBuilder.build();
return builder
.setFilesToBuild(filesToBuild)
.add(
JavaRuleOutputJarsProvider.class,
javaRuleOutputJarsProviderBuilder
.addOutputJar(classJar, iJar, srcJar)
.setJdeps(outputDepsProto)
.build())
.add(JavaSourceJarsProvider.class, javaSourceJarsProvider)
.add(
JavaRuntimeJarProvider.class,
new JavaRuntimeJarProvider(javaCommon.getJavaCompilationArtifacts().getRuntimeJars()))
.add(RunfilesProvider.class, RunfilesProvider.simple(getRunfiles()))
.add(AndroidResourcesProvider.class, resourceApk.toResourceProvider(ruleContext.getLabel()))
.add(
AndroidIdeInfoProvider.class,
createAndroidIdeInfoProvider(
ruleContext,
androidSemantics,
idlHelper,
resourceJar,
aar,
resourceApk,
zipAlignedApk,
apksUnderTest))
.add(
JavaCompilationArgsProvider.class,
JavaCompilationArgsProvider.create(
javaCompilationArgs,
recursiveJavaCompilationArgs,
compileTimeDependencyArtifacts,
NestedSetBuilder.<Artifact>emptySet(Order.STABLE_ORDER)))
.add(
JackLibraryProvider.class,
asNeverLink
? jackCompilationHelper.compileAsNeverlinkLibrary()
: jackCompilationHelper.compileAsLibrary())
.addSkylarkTransitiveInfo(AndroidSkylarkApiProvider.NAME, new AndroidSkylarkApiProvider())
.addOutputGroup(
OutputGroupProvider.HIDDEN_TOP_LEVEL, collectHiddenTopLevelArtifacts(ruleContext))
.addOutputGroup(
JavaSemantics.SOURCE_JARS_OUTPUT_GROUP,
javaSourceJarsProvider.getTransitiveSourceJars());
}
private Runfiles getRunfiles() {
// TODO(bazel-team): why return any Runfiles in the neverlink case?
if (asNeverLink) {
return new Runfiles.Builder(
ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles())
.addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES)
.build();
}
return JavaCommon.getRunfiles(
ruleContext, javaCommon.getJavaSemantics(), javaCommon.getJavaCompilationArtifacts(),
asNeverLink);
}
public static PathFragment getAssetDir(RuleContext ruleContext) {
return new PathFragment(ruleContext.attributes().get(
AndroidResourcesProvider.ResourceType.ASSETS.getAttribute() + "_dir",
Type.STRING));
}
public static NestedSet<LinkerInput> collectTransitiveNativeLibraries(
Iterable<? extends TransitiveInfoCollection> deps) {
NestedSetBuilder<LinkerInput> builder = NestedSetBuilder.stableOrder();
for (TransitiveInfoCollection dep : deps) {
AndroidNativeLibraryProvider android = dep.getProvider(AndroidNativeLibraryProvider.class);
if (android != null) {
builder.addTransitive(android.getTransitiveAndroidNativeLibraries());
continue;
}
JavaNativeLibraryProvider java = dep.getProvider(JavaNativeLibraryProvider.class);
if (java != null) {
builder.addTransitive(java.getTransitiveJavaNativeLibraries());
continue;
}
CcNativeLibraryProvider cc = dep.getProvider(CcNativeLibraryProvider.class);
if (cc != null) {
for (LinkerInput input : cc.getTransitiveCcNativeLibraries()) {
Artifact library = input.getOriginalLibraryArtifact();
String name = library.getFilename();
if (CppFileTypes.SHARED_LIBRARY.matches(name)
|| CppFileTypes.VERSIONED_SHARED_LIBRARY.matches(name)) {
builder.add(input);
}
}
continue;
}
}
return builder.build();
}
public static AndroidResourcesProvider getAndroidResources(RuleContext ruleContext) {
if (!ruleContext.attributes().has("resources", BuildType.LABEL)) {
return null;
}
TransitiveInfoCollection prerequisite = ruleContext.getPrerequisite("resources", Mode.TARGET);
if (prerequisite == null) {
return null;
}
ruleContext.ruleWarning(
"The use of the android_resources rule and the resources attribute is deprecated. "
+ "Please use the resource_files, assets, and manifest attributes of android_library.");
return prerequisite.getProvider(AndroidResourcesProvider.class);
}
/**
* Collects Java compilation arguments for this target.
*
* @param recursive Whether to scan dependencies recursively.
* @param isNeverLink Whether the target has the 'neverlink' attr.
* @param hasSrcs If false, deps are exported (deprecated behaviour)
*/
private JavaCompilationArgs collectJavaCompilationArgs(boolean recursive, boolean isNeverLink,
boolean hasSrcs) {
boolean exportDeps = !hasSrcs
&& ruleContext.getFragment(AndroidConfiguration.class).allowSrcsLessAndroidLibraryDeps();
return javaCommon.collectJavaCompilationArgs(recursive, isNeverLink, exportDeps);
}
public ImmutableList<String> getJavacOpts() {
return javaCommon.getJavacOpts();
}
public Artifact getGenClassJar() {
return genClassJar;
}
@Nullable public Artifact getGenSourceJar() {
return genSourceJar;
}
public ImmutableList<Artifact> getRuntimeJars() {
return javaCommon.getJavaCompilationArtifacts().getRuntimeJars();
}
public Artifact getResourceClassJar() {
return resourceClassJar;
}
/**
* Returns Jars produced by this rule that may go into the runtime classpath. By contrast
* {@link #getRuntimeJars()} returns the complete runtime classpath needed by this rule, including
* dependencies.
*/
public ImmutableList<Artifact> getJarsProducedForRuntime() {
return jarsProducedForRuntime;
}
public Artifact getInstrumentedJar() {
return javaCommon.getJavaCompilationArtifacts().getInstrumentedJar();
}
public NestedSet<Artifact> getTransitiveNeverLinkLibraries() {
return transitiveNeverlinkLibraries;
}
public boolean isNeverLink() {
return asNeverLink;
}
public CcLinkParamsStore getCcLinkParamsStore() {
return getCcLinkParamsStore(
javaCommon.targetsTreatedAsDeps(ClasspathType.BOTH), ImmutableList.<String>of());
}
public static CcLinkParamsStore getCcLinkParamsStore(
final Iterable<? extends TransitiveInfoCollection> deps, final Collection<String> linkOpts) {
return new CcLinkParamsStore() {
@Override
protected void collect(
CcLinkParams.Builder builder, boolean linkingStatically, boolean linkShared) {
builder.addTransitiveTargets(
deps,
// Link in Java-specific C++ code in the transitive closure
JavaCcLinkParamsProvider.TO_LINK_PARAMS,
// Link in Android-specific C++ code (e.g., android_libraries) in the transitive closure
AndroidCcLinkParamsProvider.TO_LINK_PARAMS,
// Link in non-language-specific C++ code in the transitive closure
CcLinkParamsProvider.TO_LINK_PARAMS);
builder.addLinkOpts(linkOpts);
}
};
}
/**
* Returns {@link AndroidConfiguration} in given context.
*/
static AndroidConfiguration getAndroidConfig(RuleContext context) {
return context.getConfiguration().getFragment(AndroidConfiguration.class);
}
private NestedSet<Artifact> collectHiddenTopLevelArtifacts(RuleContext ruleContext) {
NestedSetBuilder<Artifact> builder = NestedSetBuilder.stableOrder();
for (OutputGroupProvider provider :
getTransitivePrerequisites(ruleContext, Mode.TARGET, OutputGroupProvider.class)) {
builder.addTransitive(provider.getOutputGroup(OutputGroupProvider.HIDDEN_TOP_LEVEL));
}
return builder.build();
}
}
| Dedupe Jar files produced for Android binary targets for desugaring purposes.
--
MOS_MIGRATED_REVID=137305868
| src/main/java/com/google/devtools/build/lib/rules/android/AndroidCommon.java | Dedupe Jar files produced for Android binary targets for desugaring purposes. | <ide><path>rc/main/java/com/google/devtools/build/lib/rules/android/AndroidCommon.java
<ide> private JavaCompilationArgs javaCompilationArgs = JavaCompilationArgs.EMPTY_ARGS;
<ide> private JavaCompilationArgs recursiveJavaCompilationArgs = JavaCompilationArgs.EMPTY_ARGS;
<ide> private JackCompilationHelper jackCompilationHelper;
<del> private ImmutableList<Artifact> jarsProducedForRuntime;
<add> private NestedSet<Artifact> jarsProducedForRuntime;
<ide> private Artifact classJar;
<ide> private Artifact iJar;
<ide> private Artifact srcJar;
<ide> JavaCompilationArtifacts.Builder artifactsBuilder,
<ide> JavaTargetAttributes.Builder attributes,
<ide> NestedSetBuilder<Artifact> filesBuilder,
<del> ImmutableList.Builder<Artifact> jarsProducedForRuntime,
<add> NestedSetBuilder<Artifact> jarsProducedForRuntime,
<ide> boolean useRClassGenerator) throws InterruptedException {
<ide> compileResourceJar(javaSemantics, resourceApk, resourcesJar, useRClassGenerator);
<ide> // Add the compiled resource jar to the classpath of the main compilation.
<ide>
<ide> private void createJarJarActions(
<ide> JavaTargetAttributes.Builder attributes,
<del> ImmutableList.Builder<Artifact> jarsProducedForRuntime,
<add> NestedSetBuilder<Artifact> jarsProducedForRuntime,
<ide> Iterable<ResourceContainer> resourceContainers,
<ide> String originalPackage,
<ide> Artifact binaryResourcesJar) {
<ide> .setBootClassPath(bootclasspath);
<ide>
<ide> JavaCompilationArtifacts.Builder artifactsBuilder = new JavaCompilationArtifacts.Builder();
<del> ImmutableList.Builder<Artifact> jarsProducedForRuntime = ImmutableList.builder();
<add> NestedSetBuilder<Artifact> jarsProducedForRuntime = NestedSetBuilder.<Artifact>stableOrder();
<ide> NestedSetBuilder<Artifact> filesBuilder = NestedSetBuilder.<Artifact>stableOrder();
<ide>
<ide> Artifact resourcesJar = resourceApk.getResourceJavaSrcJar();
<ide> * {@link #getRuntimeJars()} returns the complete runtime classpath needed by this rule, including
<ide> * dependencies.
<ide> */
<del> public ImmutableList<Artifact> getJarsProducedForRuntime() {
<add> public NestedSet<Artifact> getJarsProducedForRuntime() {
<ide> return jarsProducedForRuntime;
<ide> }
<ide> |
|
Java | lgpl-2.1 | 53e30a5e4dabc308c4a0920ac35b9f5e51c370ee | 0 | janissl/languagetool,janissl/languagetool,meg0man/languagetool,jimregan/languagetool,lopescan/languagetool,janissl/languagetool,meg0man/languagetool,lopescan/languagetool,meg0man/languagetool,jimregan/languagetool,janissl/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,janissl/languagetool,lopescan/languagetool,jimregan/languagetool,lopescan/languagetool,lopescan/languagetool,jimregan/languagetool,languagetool-org/languagetool,meg0man/languagetool,languagetool-org/languagetool,janissl/languagetool,jimregan/languagetool,languagetool-org/languagetool,meg0man/languagetool | /* LanguageTool, a natural language style checker
* Copyright (C) 2013 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.dev.wikipedia.atom;
import org.languagetool.Language;
import java.io.IOException;
/**
* Command line tool to check the changes from a Wikipedia Atom feed with LanguageTool.
* @since 2.4
*/
final class AtomFeedCheckerCmd {
public static void main(String[] args) throws IOException, InterruptedException {
if (args.length != 2 && args.length != 3) {
System.out.println("Usage: " + AtomFeedCheckerCmd.class.getSimpleName() + " <atomFeedUrl> <sleepTime> [database.properties]");
System.out.println(" <atomFeedUrl> is a Wikipedia URL to the latest changes, for example:");
System.out.println(" https://de.wikipedia.org/w/index.php?title=Spezial:Letzte_%C3%84nderungen&feed=atom&namespace=0");
System.out.println(" <sleepTime> -1: don't loop at all (run once), 0: run in loop, other number: run in loop and");
System.out.println(" wait this many milliseconds between runs");
System.out.println(" [database.properties] (optional) is a file that defines dbUrl, dbUser, and dbPassword,");
System.out.println(" used to write the results to a database via JDBC");
System.out.println("");
System.out.println(" When the database.properties file is specified, this command will store all feed changes that");
System.out.println(" cause LanguageTool rule matches to the database. If an error is then fixed later, this will");
System.out.println(" usually also be detected and the rule match in the database will be marked as fixed. One case");
System.out.println(" where this does not work is if the context of the error gets modified before the error is fixed.");
System.out.println("");
System.out.println(" Run this command regularly so that you don't miss any changes from the feed.");
System.out.println(" As the feed may contain only the latest 50 changes, running it more often than");
System.out.println(" once per minute may be needed for active Wikipedias.");
System.exit(1);
}
String url = args[0];
String langCode = url.substring(url.indexOf("//") + 2, url.indexOf("."));
System.out.println("Using URL: " + url);
System.out.println("Language code: " + langCode);
int sleepTimeMillis = Integer.parseInt(args[1]);
System.out.println("Sleep time: " + sleepTimeMillis + "ms (-1 = don't loop)");
DatabaseConfig databaseConfig = null;
if (args.length == 3) {
String propFile = args[2];
databaseConfig = new DatabaseConfig(propFile);
System.out.println("Writing results to database at: " + databaseConfig.getUrl());
}
Language language = Language.getLanguageForShortName(langCode);
AtomFeedChecker atomFeedChecker = new AtomFeedChecker(language, databaseConfig);
while (true) {
long startTime = System.currentTimeMillis();
try {
atomFeedChecker.runCheck(url);
System.out.println("Run time: " + (System.currentTimeMillis() - startTime) + "ms");
if (sleepTimeMillis == -1) {
// don't loop at all
break;
} else {
System.out.println("Sleeping " + sleepTimeMillis + "ms...");
Thread.sleep(sleepTimeMillis);
}
} catch (Exception e) {
// e.g. 50x HTTP errors, network problems
e.printStackTrace();
System.out.println("Sleeping " + sleepTimeMillis + "ms...");
Thread.sleep(sleepTimeMillis);
}
}
}
}
| languagetool-wikipedia/src/main/java/org/languagetool/dev/wikipedia/atom/AtomFeedCheckerCmd.java | /* LanguageTool, a natural language style checker
* Copyright (C) 2013 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.dev.wikipedia.atom;
import org.languagetool.Language;
import java.io.IOException;
/**
* Command line tool to check the changes from a Wikipedia Atom feed with LanguageTool.
* @since 2.4
*/
final class AtomFeedCheckerCmd {
public static void main(String[] args) throws IOException, InterruptedException {
if (args.length != 2 && args.length != 3) {
System.out.println("Usage: " + AtomFeedCheckerCmd.class.getSimpleName() + " <atomFeedUrl> <sleepTime> [database.properties]");
System.out.println(" <atomFeedUrl> is a Wikipedia URL to the latest changes, for example:");
System.out.println(" https://de.wikipedia.org/w/index.php?title=Spezial:Letzte_%C3%84nderungen&feed=atom&namespace=0");
System.out.println(" <sleepTime> -1: don't loop at all (run once), 0: run in loop, other number: run in loop and");
System.out.println(" wait this many milliseconds between runs");
System.out.println(" [database.properties] (optional) is a file that defines dbUrl, dbUser, and dbPassword,");
System.out.println(" used to write the results to a database via JDBC");
System.out.println("");
System.out.println(" When the database.properties file is specified, this command will store all feed changes that");
System.out.println(" cause LanguageTool rule matches to the database. If an error is then fixed later, this will");
System.out.println(" usually also be detected and the rule match in the database will be marked as fixed. One case");
System.out.println(" where this does not work is if the context of the error gets modified before the error is fixed.");
System.out.println("");
System.out.println(" Run this command regularly so that you don't miss any changes from the feed.");
System.out.println(" As the feed may contain only the latest 50 changes, running it more often than");
System.out.println(" once per minute may be needed for active Wikipedias.");
System.exit(1);
}
String url = args[0];
String langCode = url.substring(url.indexOf("//") + 2, url.indexOf("."));
System.out.println("Using URL: " + url);
System.out.println("Language code: " + langCode);
int sleepTimeMillis = Integer.parseInt(args[1]);
System.out.println("Sleep time: " + sleepTimeMillis + "ms (-1 = don't loop)");
DatabaseConfig databaseConfig = null;
if (args.length == 3) {
String propFile = args[2];
databaseConfig = new DatabaseConfig(propFile);
System.out.println("Writing results to database at: " + databaseConfig.getUrl());
}
Language language = Language.getLanguageForShortName(langCode);
AtomFeedChecker atomFeedChecker = new AtomFeedChecker(language, databaseConfig);
while (true) {
long startTime = System.currentTimeMillis();
try {
atomFeedChecker.runCheck(url);
System.out.println("Run time: " + (System.currentTimeMillis() - startTime) + "ms");
if (sleepTimeMillis == -1) {
// don't loop at all
break;
} else {
System.out.println("Sleeping " + sleepTimeMillis + "ms...");
Thread.sleep(sleepTimeMillis);
}
} catch (IOException e) {
// e.g. 50x HTTP errors
e.printStackTrace();
System.out.println("Sleeping " + sleepTimeMillis + "ms...");
Thread.sleep(sleepTimeMillis);
}
}
}
}
| catch all exceptions and continue so we don't crash because of network problems
| languagetool-wikipedia/src/main/java/org/languagetool/dev/wikipedia/atom/AtomFeedCheckerCmd.java | catch all exceptions and continue so we don't crash because of network problems | <ide><path>anguagetool-wikipedia/src/main/java/org/languagetool/dev/wikipedia/atom/AtomFeedCheckerCmd.java
<ide> System.out.println("Sleeping " + sleepTimeMillis + "ms...");
<ide> Thread.sleep(sleepTimeMillis);
<ide> }
<del> } catch (IOException e) {
<del> // e.g. 50x HTTP errors
<add> } catch (Exception e) {
<add> // e.g. 50x HTTP errors, network problems
<ide> e.printStackTrace();
<ide> System.out.println("Sleeping " + sleepTimeMillis + "ms...");
<ide> Thread.sleep(sleepTimeMillis); |
|
Java | apache-2.0 | 932818b243b1ca296af27857765ae45b49bb78b6 | 0 | kaen/Terasology,kartikey0303/Terasology,Halamix2/Terasology,CC4401-TeraCity/TeraCity,MarcinSc/Terasology,MovingBlocks/Terasology,dannyzhou98/Terasology,Josharias/Terasology,Halamix2/Terasology,frankpunx/Terasology,samuto/Terasology,Josharias/Terasology,mertserezli/Terasology,indianajohn/Terasology,samuto/Terasology,Felges/Terasology,jacklotusho/Terasology,frankpunx/Terasology,AWildBeard/Terasology,Vizaxo/Terasology,MovingBlocks/Terasology,MovingBlocks/Terasology,dannyzhou98/Terasology,leelib/Terasology,Ciclop/Terasology,Vizaxo/Terasology,AWildBeard/Terasology,dimamo5/Terasology,sceptross/Terasology,immortius/Terasology,kartikey0303/Terasology,jacklotusho/Terasology,flo/Terasology,CC4401-TeraCity/TeraCity,flo/Terasology,kaen/Terasology,DPirate/Terasology,neshume/Terasology,neshume/Terasology,Nanoware/Terasology,Nanoware/Terasology,immortius/Terasology,dimamo5/Terasology,indianajohn/Terasology,Malanius/Terasology,MarcinSc/Terasology,mertserezli/Terasology,Ciclop/Terasology,sceptross/Terasology,DPirate/Terasology,leelib/Terasology,Nanoware/Terasology,Felges/Terasology,Malanius/Terasology | /*
* Copyright 2013 MovingBlocks
*
* 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 com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.config.ModuleConfig;
import org.terasology.engine.ComponentSystemManager;
import org.terasology.engine.TerasologyEngine;
import org.terasology.engine.module.ModuleManager;
import org.terasology.entitySystem.systems.ComponentSystem;
import org.terasology.module.Module;
import org.terasology.registry.CoreRegistry;
import org.terasology.engine.EngineTime;
import org.terasology.engine.paths.PathManager;
import org.terasology.persistence.StorageManager;
import org.terasology.world.WorldProvider;
import org.terasology.world.biomes.Biome;
import org.terasology.world.biomes.BiomeManager;
import org.terasology.world.block.BlockManager;
import org.terasology.world.block.family.BlockFamily;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Immortius
*/
public class Game {
private static final Logger logger = LoggerFactory.getLogger(Game.class);
private EngineTime time;
private String name = "";
private String seed = "";
private TerasologyEngine terasologyEngine;
public Game(TerasologyEngine terasologyEngine, EngineTime time) {
this.terasologyEngine = terasologyEngine;
this.time = time;
}
public void load(GameManifest manifest) {
this.name = manifest.getTitle();
this.seed = manifest.getSeed();
try {
PathManager.getInstance().setCurrentSaveTitle(manifest.getTitle());
} catch (IOException e) {
logger.error("Failed to set save path", e);
}
time.setGameTime(manifest.getTime());
}
public void save() {
save(true);
}
public void save(boolean flushAndShutdownStorageManager) {
ComponentSystemManager componentSystemManager = CoreRegistry.get(ComponentSystemManager.class);
for (ComponentSystem sys : componentSystemManager.iterateAll()) {
sys.preSave();
}
terasologyEngine.stopThreads();
StorageManager storageManager = CoreRegistry.get(StorageManager.class);
if (storageManager != null) {
GameManifest gameManifest = createGameManifest();
saveGameManifest(gameManifest);
try {
storageManager.flush();
} catch (IOException e) {
logger.error("Failed to save game", e);
}
storageManager.shutdown();
}
terasologyEngine.restartThreads();
for (ComponentSystem sys : componentSystemManager.iterateAll()) {
sys.postSave();
}
}
public void saveGameManifest(GameManifest gameManifest) {
try {
GameManifest.save(PathManager.getInstance().getCurrentSavePath().resolve(GameManifest.DEFAULT_FILE_NAME), gameManifest);
} catch (IOException e) {
logger.error("Failed to save world manifest", e);
}
}
public GameManifest createGameManifest() {
BlockManager blockManager = CoreRegistry.get(BlockManager.class);
BiomeManager biomeManager = CoreRegistry.get(BiomeManager.class);
WorldProvider worldProvider = CoreRegistry.get(WorldProvider.class);
GameManifest gameManifest = new GameManifest(name, seed, time.getGameTimeInMs());
for (Module module : CoreRegistry.get(ModuleManager.class).getEnvironment()) {
gameManifest.addModule(module.getId(), module.getVersion());
}
List<String> registeredBlockFamilies = Lists.newArrayList();
for (BlockFamily family : blockManager.listRegisteredBlockFamilies()) {
registeredBlockFamilies.add(family.getURI().toString());
}
gameManifest.setRegisteredBlockFamilies(registeredBlockFamilies);
gameManifest.setBlockIdMap(blockManager.getBlockIdMap());
List<Biome> biomes = biomeManager.getBiomes();
Map<String, Short> biomeIdMap = new HashMap<>(biomes.size());
for (Biome biome : biomes) {
short shortId = biomeManager.getBiomeShortId(biome);
String id = biomeManager.getBiomeId(biome);
biomeIdMap.put(id, shortId);
}
gameManifest.setBiomeIdMap(biomeIdMap);
gameManifest.addWorld(worldProvider.getWorldInfo());
return gameManifest;
}
}
| engine/src/main/java/org/terasology/game/Game.java | /*
* Copyright 2013 MovingBlocks
*
* 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 com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.config.ModuleConfig;
import org.terasology.engine.ComponentSystemManager;
import org.terasology.engine.TerasologyEngine;
import org.terasology.engine.module.ModuleManager;
import org.terasology.entitySystem.systems.ComponentSystem;
import org.terasology.module.Module;
import org.terasology.registry.CoreRegistry;
import org.terasology.engine.EngineTime;
import org.terasology.engine.paths.PathManager;
import org.terasology.persistence.StorageManager;
import org.terasology.world.WorldProvider;
import org.terasology.world.biomes.Biome;
import org.terasology.world.biomes.BiomeManager;
import org.terasology.world.block.BlockManager;
import org.terasology.world.block.family.BlockFamily;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Immortius
*/
public class Game {
private static final Logger logger = LoggerFactory.getLogger(Game.class);
private EngineTime time;
private String name = "";
private String seed = "";
private TerasologyEngine terasologyEngine;
public Game(TerasologyEngine terasologyEngine, EngineTime time) {
this.terasologyEngine = terasologyEngine;
this.time = time;
}
public void load(GameManifest manifest) {
this.name = manifest.getTitle();
this.seed = manifest.getSeed();
try {
PathManager.getInstance().setCurrentSaveTitle(manifest.getTitle());
} catch (IOException e) {
logger.error("Failed to set save path", e);
}
time.setGameTime(manifest.getTime());
}
public void save() {
save(true);
}
public void save(boolean flushAndShutdownStorageManager) {
ComponentSystemManager componentSystemManager = CoreRegistry.get(ComponentSystemManager.class);
for (ComponentSystem sys : componentSystemManager.iterateAll()) {
sys.preSave();
}
terasologyEngine.stopThreads();
StorageManager storageManager = CoreRegistry.get(StorageManager.class);
if (storageManager != null) {
BlockManager blockManager = CoreRegistry.get(BlockManager.class);
BiomeManager biomeManager = CoreRegistry.get(BiomeManager.class);
WorldProvider worldProvider = CoreRegistry.get(WorldProvider.class);
GameManifest gameManifest = new GameManifest(name, seed, time.getGameTimeInMs());
for (Module module : CoreRegistry.get(ModuleManager.class).getEnvironment()) {
gameManifest.addModule(module.getId(), module.getVersion());
}
List<String> registeredBlockFamilies = Lists.newArrayList();
for (BlockFamily family : blockManager.listRegisteredBlockFamilies()) {
registeredBlockFamilies.add(family.getURI().toString());
}
gameManifest.setRegisteredBlockFamilies(registeredBlockFamilies);
gameManifest.setBlockIdMap(blockManager.getBlockIdMap());
List<Biome> biomes = biomeManager.getBiomes();
Map<String, Short> biomeIdMap = new HashMap<>(biomes.size());
for (Biome biome : biomes) {
short shortId = biomeManager.getBiomeShortId(biome);
String id = biomeManager.getBiomeId(biome);
biomeIdMap.put(id, shortId);
}
gameManifest.setBiomeIdMap(biomeIdMap);
gameManifest.addWorld(worldProvider.getWorldInfo());
try {
GameManifest.save(PathManager.getInstance().getCurrentSavePath().resolve(GameManifest.DEFAULT_FILE_NAME), gameManifest);
} catch (IOException e) {
logger.error("Failed to save world manifest", e);
}
if (flushAndShutdownStorageManager) {
try {
storageManager.flush();
} catch (IOException e) {
logger.error("Failed to save game", e);
}
storageManager.shutdown();
}
}
terasologyEngine.restartThreads();
for (ComponentSystem sys : componentSystemManager.iterateAll()) {
sys.postSave();
}
}
}
| Extracted createGAmeManifest and saveGameManifest methods.
| engine/src/main/java/org/terasology/game/Game.java | Extracted createGAmeManifest and saveGameManifest methods. | <ide><path>ngine/src/main/java/org/terasology/game/Game.java
<ide>
<ide> StorageManager storageManager = CoreRegistry.get(StorageManager.class);
<ide> if (storageManager != null) {
<del> BlockManager blockManager = CoreRegistry.get(BlockManager.class);
<del> BiomeManager biomeManager = CoreRegistry.get(BiomeManager.class);
<del> WorldProvider worldProvider = CoreRegistry.get(WorldProvider.class);
<del>
<del> GameManifest gameManifest = new GameManifest(name, seed, time.getGameTimeInMs());
<del> for (Module module : CoreRegistry.get(ModuleManager.class).getEnvironment()) {
<del> gameManifest.addModule(module.getId(), module.getVersion());
<add> GameManifest gameManifest = createGameManifest();
<add> saveGameManifest(gameManifest);
<add> try {
<add> storageManager.flush();
<add> } catch (IOException e) {
<add> logger.error("Failed to save game", e);
<ide> }
<del>
<del> List<String> registeredBlockFamilies = Lists.newArrayList();
<del> for (BlockFamily family : blockManager.listRegisteredBlockFamilies()) {
<del> registeredBlockFamilies.add(family.getURI().toString());
<del> }
<del> gameManifest.setRegisteredBlockFamilies(registeredBlockFamilies);
<del> gameManifest.setBlockIdMap(blockManager.getBlockIdMap());
<del> List<Biome> biomes = biomeManager.getBiomes();
<del> Map<String, Short> biomeIdMap = new HashMap<>(biomes.size());
<del> for (Biome biome : biomes) {
<del> short shortId = biomeManager.getBiomeShortId(biome);
<del> String id = biomeManager.getBiomeId(biome);
<del> biomeIdMap.put(id, shortId);
<del> }
<del> gameManifest.setBiomeIdMap(biomeIdMap);
<del>
<del> gameManifest.addWorld(worldProvider.getWorldInfo());
<del>
<del> try {
<del> GameManifest.save(PathManager.getInstance().getCurrentSavePath().resolve(GameManifest.DEFAULT_FILE_NAME), gameManifest);
<del> } catch (IOException e) {
<del> logger.error("Failed to save world manifest", e);
<del> }
<del> if (flushAndShutdownStorageManager) {
<del> try {
<del> storageManager.flush();
<del> } catch (IOException e) {
<del> logger.error("Failed to save game", e);
<del> }
<del> storageManager.shutdown();
<del> }
<add> storageManager.shutdown();
<ide> }
<ide>
<ide> terasologyEngine.restartThreads();
<ide>
<ide>
<ide> }
<add>
<add> public void saveGameManifest(GameManifest gameManifest) {
<add> try {
<add> GameManifest.save(PathManager.getInstance().getCurrentSavePath().resolve(GameManifest.DEFAULT_FILE_NAME), gameManifest);
<add> } catch (IOException e) {
<add> logger.error("Failed to save world manifest", e);
<add> }
<add> }
<add>
<add> public GameManifest createGameManifest() {
<add> BlockManager blockManager = CoreRegistry.get(BlockManager.class);
<add> BiomeManager biomeManager = CoreRegistry.get(BiomeManager.class);
<add> WorldProvider worldProvider = CoreRegistry.get(WorldProvider.class);
<add>
<add> GameManifest gameManifest = new GameManifest(name, seed, time.getGameTimeInMs());
<add> for (Module module : CoreRegistry.get(ModuleManager.class).getEnvironment()) {
<add> gameManifest.addModule(module.getId(), module.getVersion());
<add> }
<add>
<add> List<String> registeredBlockFamilies = Lists.newArrayList();
<add> for (BlockFamily family : blockManager.listRegisteredBlockFamilies()) {
<add> registeredBlockFamilies.add(family.getURI().toString());
<add> }
<add> gameManifest.setRegisteredBlockFamilies(registeredBlockFamilies);
<add> gameManifest.setBlockIdMap(blockManager.getBlockIdMap());
<add> List<Biome> biomes = biomeManager.getBiomes();
<add> Map<String, Short> biomeIdMap = new HashMap<>(biomes.size());
<add> for (Biome biome : biomes) {
<add> short shortId = biomeManager.getBiomeShortId(biome);
<add> String id = biomeManager.getBiomeId(biome);
<add> biomeIdMap.put(id, shortId);
<add> }
<add> gameManifest.setBiomeIdMap(biomeIdMap);
<add> gameManifest.addWorld(worldProvider.getWorldInfo());
<add> return gameManifest;
<add> }
<ide> } |
|
JavaScript | mit | 7835708907254b2ac3fca475ca9e78ae15ca01f9 | 0 | victor4l/PostIt,victor4l/PostIt | import supertest from 'supertest';
import dotenv from 'dotenv';
import models from '../models';
import app from '../index';
import fixtures from '../fixtures/testFixtures';
dotenv.config();
const request = supertest(app);
describe('PostIt Tests', () => {
describe('Database connection tests', () => {
// Sync database before commencing testing
beforeEach((done) => {
models.sequelize.sync();
done();
});
it('ensures database connection is established', (done) => {
models.sequelize.authenticate().then((err) => {
expect(err).toEqual(null);
done();
});
});
});
describe('Testing routes with incorrect data', () => {
it('returns an error if a user is to be added to a non-existent group id', (done) => {
request
.post('/api/group/unknowngroupid/user')
.send(fixtures.newUser)
.expect((res) => {
expect(res.body.message).toEqual('Group not found');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('returns an error a non-existent user attempts to create a group', (done) => {
request
.post('/api/group/')
.send({
userId: '7229aca1-55f4-4873-86d3-0774ec7a0d7e', // Unregisted user Id
title: 'New Group',
description: 'A group created by an unregisterd user'
})
.expect((res) => {
expect(res.body.message).toEqual('User not found');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('returns an error if a message is to be posted to a non-existent group id', (done) => {
request
.post('/api/group/unknowngroupid/message')
.send(fixtures.newMessage)
.expect((res) => {
expect(res.body.message).toEqual('Group not found');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('returns an error if you attempt to load messages from a non-existent group id', (done) => {
request
.get('/api/group/unknowngroupid/messages')
.expect((res) => {
expect(res.body.message).toEqual('Group not found');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('returns an error if you attempt to load members from a non-existent group id', (done) => {
request
.get('/api/group/unknowngroupid/members')
.expect((res) => {
expect(res.body.message).toEqual('Group not found');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('returns error if you attempt to load the groups for a non-existent user', (done) => {
request
.get('/api/group/nonexistentuserId/groups')
.expect((res) => {
expect(res.body.message).toEqual('User not found');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('Authentication routes test', () => {
const newUser = fixtures.newUser;
const registeredUser = fixtures.registeredUser;
const userWithIncorrectPassword = fixtures.userWithIncorrectPassword;
let userId;
// Clean up User table, and then create sample user
beforeEach((done) => {
models.User.destroy({
where: {},
cascade: true,
truncate: true
}).then(() => {
models.User.create(newUser).then((createdUser) => {
userId = createdUser.id;
done();
});
});
});
it('ensures proper response for successful user sign in', (done) => {
request
.post('/api/user/signin')
.send(registeredUser)
.expect((res) => {
expect(res.body.user.email).toEqual(registeredUser.email);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures proper response for incorrect auth details', (done) => {
request
.post('/api/user/signin')
.send(userWithIncorrectPassword)
.expect((res) => {
expect(res.body.message).toEqual('Error During Signin');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures proper response if user creates a group with incomplete data', (done) => {
request
.post('/api/group')
.send({ userId })
.expect((res) => {
expect(res.body.message).toEqual('Group not created');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures all groups a user belongs to can be loaded', (done) => {
request
.get(`/api/group/${userId}/groups`)
.expect((res) => {
const isArray = res.body instanceof Array;
expect(isArray).toEqual(true);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('Tests for User creation routes', () => {
// Clean up database before commencing testing
beforeEach((done) => {
models.User.destroy({
where: {},
truncate: true,
cascade: true
}).then(() => { done(); });
});
it('ensures proper response for successful user sign up', (done) => {
request
.post('/api/user/signup')
.send(fixtures.newUser)
.expect((res) => {
expect(res.body.error).toEqual(null);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures proper response for sign up with incorrect data', (done) => {
request
.post('/api/user/signup')
.send(fixtures.newUserWithMissingData)
.expect((res) => {
expect(res.body.message).toEqual('Error During Signup');
done();
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('Tests for Group CRUD operation routes', () => {
// Delete previous records and populate db with test data
let groupId;
const newGroup = fixtures.newGroup;
const newGroup2 = fixtures.newGroup2;
const newGroupWithMultipleMembers = fixtures.newGroupWithMultipleMembers;
const newGroupWithSingleMember = fixtures.newGroupWithSingleMember;
beforeEach((done) => {
models.User.destroy({
where: {},
truncate: true,
cascade: true
}).then(() => {
models.Group.destroy({
where: {},
truncate: true,
cascade: true
}).then(() => {
models.User.create(fixtures.newUser).then((createdUser) => {
newGroup.userId = createdUser.id;
newGroup2.userId = createdUser.id;
newGroupWithMultipleMembers.userId = createdUser.id;
newGroupWithSingleMember.userId = createdUser.id;
}).then(() => {
models.User.bulkCreate([fixtures.newUser2, fixtures.newUser3]).then(() => {
models.Group.create(newGroup).then((createdGroup) => {
groupId = createdGroup.id;
done();
});
});
});
});
});
});
it('ensures successfull group creation', (done) => {
request
.post('/api/group')
.send(fixtures.newGroup2)
.expect((res) => {
console.log(res.body);
expect(res.body.title).toEqual(fixtures.newGroup2.title);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures a user can be added to a group after it is created', (done) => {
request
.post(`/api/group/${groupId}/user`)
.send({ email: '[email protected]' })
.expect((res) => {
expect(res.body.email).toEqual('[email protected]');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('returns an empty object if an unregisterd user is to be added to a group', (done) => {
request
.post(`/api/group/${groupId}/user`)
.send({ email: '[email protected]' })
.expect({ message: 'User not found' })
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures group can be created with no members added initially', (done) => {
request
.post('/api/group')
.send(fixtures.newGroup2)
.expect((res) => {
expect(res.body.title).toEqual(fixtures.newGroup2.title);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures group can be created with a single member added initially', (done) => {
request
.post('/api/group')
.send(fixtures.newGroupWithSingleMember)
.expect((res) => {
expect(res.body.title).toEqual(fixtures.newGroupWithSingleMember.title);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures group can be created with multiple members added initially', (done) => {
request
.post('/api/group')
.send(fixtures.newGroupWithMultipleMembers)
.expect((res) => {
expect(res.body.title).toEqual(fixtures.newGroupWithMultipleMembers.title);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('General app activities', () => {
it('ensures sensible response for incorrect route', (done) => {
request
.get('/unregistered')
.expect({ message: 'Api up and running' })
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures all registered users can be loaded from the database', (done) => {
request
.get('/api/group/members')
.expect((res) => {
const isArray = res.body instanceof Array;
expect(isArray).toEqual(true);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('Tests for CRUD activities in a particular group', () => {
let groupId;
const newMessage = fixtures.newMessage;
const newMessageForRoute = fixtures.newMessageForRoute;
beforeEach((done) => {
models.Group.destroy({
where: {},
cascade: true,
truncate: true
}).then(() => {
models.Group.create(fixtures.newGroup).then((createdGroup) => {
groupId = createdGroup.id;
newMessage.groupId = createdGroup.id;
models.Message.create(newMessage).then(() => {
done();
});
});
});
});
it('ensures successfull posting of messages to a particular group', (done) => {
request
.post(`/api/group/${groupId}/message`)
.send(newMessageForRoute)
.expect((res) => {
expect(res.body.body).toEqual(newMessageForRoute.message);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures all messages for a particular group can be loaded successfully', (done) => {
request
.get(`/api/group/${groupId}/messages`)
.expect((res) => {
const isArray = res.body instanceof Array;
expect(isArray).toEqual(true);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures all members of a particular group can be loaded successfully', (done) => {
request
.get(`/api/group/${groupId}/members`)
.expect((res) => {
const isArray = res.body instanceof Array;
expect(isArray).toEqual(true);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('Model tests', () => {
const newUser = fixtures.newUser;
const newGroup = fixtures.newGroup;
const newMessage = fixtures.newMessage;
let groupId;
beforeEach((done) => {
models.User.destroy({
where: {},
truncate: true,
cascade: true
}).then(() => {
models.Group.destroy({
where: {},
truncate: true,
cascade: true
}).then(() => {
models.Group.create(fixtures.newGroup).then((createdGroup) => {
groupId = createdGroup.id;
newMessage.groupId = groupId;
done();
});
});
});
});
it('ensures User model is created correctly', (done) => {
models.User.create(newUser).then((createdUser) => {
expect(createdUser.email).toEqual(newUser.email);
done();
});
});
it('ensures Group model is created successfully', (done) => {
models.Group.create(fixtures.newGroup2).then((createdGroup) => {
expect(createdGroup.createdBy).toEqual('John Doe');
done();
});
});
it('ensures Message model is created successfully', (done) => {
models.Message.create(newMessage).then((createdMessage) => {
expect(createdMessage.sentBy).toEqual('John Smith');
// Close connections to server and database
app.close();
models.sequelize.close();
done();
});
});
});
});
| server/tests/tests.js | import supertest from 'supertest';
import dotenv from 'dotenv';
import models from '../models';
import app from '../index';
import fixtures from '../fixtures/testFixtures';
dotenv.config();
const request = supertest(app);
describe('PostIt Tests', () => {
describe('Database connection tests', () => {
// Sync database before commencing testing
beforeEach((done) => {
models.sequelize.sync();
done();
});
it('ensures database connection is established', (done) => {
models.sequelize.authenticate().then((err) => {
expect(err).toEqual(null);
done();
});
});
});
describe('Testing routes with incorrect data', () => {
it('returns an error if a user is to be added to a non-existent group id', (done) => {
request
.post('/api/group/unknowngroupid/user')
.send(fixtures.newUser)
.expect((res) => {
expect(res.body.message).toEqual('Group not found');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('returns an error a non-existent user attempts to create a group', (done) => {
request
.post('/api/group/')
.send({
userId: '7229aca1-55f4-4873-86d3-0774ec7a0d7e', // Unregisted user Id
title: 'New Group',
description: 'A group created by an unregisterd user'
})
.expect((res) => {
expect(res.body.message).toEqual('User not found');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('returns an error if a message is to be posted to a non-existent group id', (done) => {
request
.post('/api/group/unknowngroupid/message')
.send(fixtures.newMessage)
.expect((res) => {
expect(res.body.message).toEqual('Group not found');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('returns an error if you attempt to load messages from a non-existent group id', (done) => {
request
.get('/api/group/unknowngroupid/messages')
.expect((res) => {
expect(res.body.message).toEqual('Group not found');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('returns an error if you attempt to load members from a non-existent group id', (done) => {
request
.get('/api/group/unknowngroupid/members')
.expect((res) => {
expect(res.body.message).toEqual('Group not found');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('returns error if you attempt to load the groups for a non-existent user', (done) => {
request
.get('/api/group/nonexistentuserId/groups')
.expect((res) => {
expect(res.body.message).toEqual('User not found');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('Authentication routes test', () => {
const newUser = fixtures.newUser;
const registeredUser = fixtures.registeredUser;
const userWithIncorrectPassword = fixtures.userWithIncorrectPassword;
let userId;
// Clean up User table, and then create sample user
beforeEach((done) => {
models.User.destroy({
where: {},
cascade: true,
truncate: true
}).then(() => {
models.User.create(newUser).then((createdUser) => {
userId = createdUser.id;
done();
});
});
});
it('ensures proper response for successful user sign in', (done) => {
request
.post('/api/user/signin')
.send(registeredUser)
.expect((res) => {
expect(res.body.user.email).toEqual(registeredUser.email);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures proper response for incorrect auth details', (done) => {
request
.post('/api/user/signin')
.send(userWithIncorrectPassword)
.expect((res) => {
expect(res.body.message).toEqual('Error During Signin');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures proper response if user creates a group with incomplete data', (done) => {
request
.post('/api/group')
.send({ userId })
.expect((res) => {
expect(res.body.message).toEqual('Group not created');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures all groups a user belongs to can be loaded', (done) => {
request
.get(`/api/group/${userId}/groups`)
.expect((res) => {
const isArray = res.body instanceof Array;
expect(isArray).toEqual(true);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('Tests for User creation routes', () => {
// Clean up database before commencing testing
beforeEach((done) => {
models.User.destroy({
where: {},
truncate: true,
cascade: true
}).then(() => { done(); });
});
it('ensures proper response for successful user sign up', (done) => {
request
.post('/api/user/signup')
.send(fixtures.newUser)
.expect((res) => {
expect(res.body.error).toEqual(null);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures proper response for sign up with incorrect data', (done) => {
request
.post('/api/user/signup')
.send(fixtures.newUserWithMissingData)
.expect((res) => {
expect(res.body.message).toEqual('Error During Signup');
done();
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('Tests for Group CRUD operation routes', () => {
// Delete previous records and populate db with test data
let groupId;
const newGroup = fixtures.newGroup;
const newGroupWithMultipleMembers = fixtures.newGroupWithMultipleMembers;
const newGroupWithSingleMember = fixtures.newGroupWithSingleMember;
beforeEach((done) => {
models.User.destroy({
where: {},
truncate: true,
cascade: true
}).then(() => {
models.Group.destroy({
where: {},
truncate: true,
cascade: true
}).then(() => {
models.User.create(fixtures.newUser).then((createdUser) => {
newGroup.userId = createdUser.id;
newGroupWithMultipleMembers.userId = createdUser.id;
newGroupWithSingleMember.userId = createdUser.id;
}).then(() => {
models.User.bulkCreate([fixtures.newUser2, fixtures.newUser3]).then(() => {
models.Group.create(newGroup).then((createdGroup) => {
groupId = createdGroup.id;
done();
});
});
});
});
});
});
it('ensures successfull group creation', (done) => {
request
.post('/api/group')
.send(fixtures.newGroup)
.expect((res) => {
expect(res.body.title).toEqual(fixtures.newGroup.title);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures a user can be added to a group after it is created', (done) => {
request
.post(`/api/group/${groupId}/user`)
.send({ email: '[email protected]' })
.expect((res) => {
expect(res.body.email).toEqual('[email protected]');
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('returns an empty object if an unregisterd user is to be added to a group', (done) => {
request
.post(`/api/group/${groupId}/user`)
.send({ email: '[email protected]' })
.expect({})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures group can be created with no members added initially', (done) => {
request
.post('/api/group')
.send(fixtures.newGroup)
.expect((res) => {
expect(res.body.title).toEqual(fixtures.newGroup.title);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures group can be created with a single member added initially', (done) => {
request
.post('/api/group')
.send(fixtures.newGroupWithSingleMember)
.expect((res) => {
expect(res.body.title).toEqual(fixtures.newGroupWithSingleMember.title);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures group can be created with multiple members added initially', (done) => {
request
.post('/api/group')
.send(fixtures.newGroupWithMultipleMembers)
.expect((res) => {
expect(res.body.title).toEqual(fixtures.newGroupWithMultipleMembers.title);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('General app activities', () => {
it('ensures sensible response for incorrect route', (done) => {
request
.get('/unregistered')
.expect({ message: 'Api up and running' })
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures all registered users can be loaded from the database', (done) => {
request
.get('/api/group/members')
.expect((res) => {
const isArray = res.body instanceof Array;
expect(isArray).toEqual(true);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('Tests for CRUD activities in a particular group', () => {
let groupId;
const newMessage = fixtures.newMessage;
const newMessageForRoute = fixtures.newMessageForRoute;
beforeEach((done) => {
models.Group.destroy({
where: {},
cascade: true,
truncate: true
}).then(() => {
models.Group.create(fixtures.newGroup).then((createdGroup) => {
groupId = createdGroup.id;
newMessage.groupId = createdGroup.id;
models.Message.create(newMessage).then(() => {
done();
});
});
});
});
it('ensures successfull posting of messages to a particular group', (done) => {
request
.post(`/api/group/${groupId}/message`)
.send(newMessageForRoute)
.expect((res) => {
expect(res.body.body).toEqual(newMessageForRoute.message);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures all messages for a particular group can be loaded successfully', (done) => {
request
.get(`/api/group/${groupId}/messages`)
.expect((res) => {
const isArray = res.body instanceof Array;
expect(isArray).toEqual(true);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
it('ensures all members of a particular group can be loaded successfully', (done) => {
request
.get(`/api/group/${groupId}/members`)
.expect((res) => {
const isArray = res.body instanceof Array;
expect(isArray).toEqual(true);
})
.end((err) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('Model tests', () => {
const newUser = fixtures.newUser;
const newGroup = fixtures.newGroup;
const newMessage = fixtures.newMessage;
let groupId;
beforeEach((done) => {
models.User.destroy({
where: {},
truncate: true,
cascade: true
}).then(() => {
models.Group.destroy({
where: {},
truncate: true,
cascade: true
}).then(() => {
models.Group.create(fixtures.newGroup).then((createdGroup) => {
groupId = createdGroup.id;
newMessage.groupId = groupId;
done();
});
});
});
});
it('ensures User model is created correctly', (done) => {
models.User.create(newUser).then((createdUser) => {
expect(createdUser.email).toEqual(newUser.email);
done();
});
});
it('ensures Group model is created successfully', (done) => {
models.Group.create(newGroup).then((createdGroup) => {
expect(createdGroup.createdBy).toEqual('Jane Doe');
done();
});
});
it('ensures Message model is created successfully', (done) => {
models.Message.create(newMessage).then((createdMessage) => {
expect(createdMessage.sentBy).toEqual('John Smith');
// Close connections to server and database
app.close();
models.sequelize.close();
done();
});
});
});
});
| modify test suite to make up for file changes
| server/tests/tests.js | modify test suite to make up for file changes | <ide><path>erver/tests/tests.js
<ide> // Delete previous records and populate db with test data
<ide> let groupId;
<ide> const newGroup = fixtures.newGroup;
<add> const newGroup2 = fixtures.newGroup2;
<ide> const newGroupWithMultipleMembers = fixtures.newGroupWithMultipleMembers;
<ide> const newGroupWithSingleMember = fixtures.newGroupWithSingleMember;
<ide> beforeEach((done) => {
<ide> }).then(() => {
<ide> models.User.create(fixtures.newUser).then((createdUser) => {
<ide> newGroup.userId = createdUser.id;
<add> newGroup2.userId = createdUser.id;
<ide> newGroupWithMultipleMembers.userId = createdUser.id;
<ide> newGroupWithSingleMember.userId = createdUser.id;
<ide> }).then(() => {
<ide> it('ensures successfull group creation', (done) => {
<ide> request
<ide> .post('/api/group')
<del> .send(fixtures.newGroup)
<del> .expect((res) => {
<del> expect(res.body.title).toEqual(fixtures.newGroup.title);
<add> .send(fixtures.newGroup2)
<add> .expect((res) => {
<add> console.log(res.body);
<add> expect(res.body.title).toEqual(fixtures.newGroup2.title);
<ide> })
<ide> .end((err) => {
<ide> if (err) {
<ide> request
<ide> .post(`/api/group/${groupId}/user`)
<ide> .send({ email: '[email protected]' })
<del> .expect({})
<add> .expect({ message: 'User not found' })
<ide> .end((err) => {
<ide> if (err) {
<ide> return done(err);
<ide> it('ensures group can be created with no members added initially', (done) => {
<ide> request
<ide> .post('/api/group')
<del> .send(fixtures.newGroup)
<del> .expect((res) => {
<del> expect(res.body.title).toEqual(fixtures.newGroup.title);
<add> .send(fixtures.newGroup2)
<add> .expect((res) => {
<add> expect(res.body.title).toEqual(fixtures.newGroup2.title);
<ide> })
<ide> .end((err) => {
<ide> if (err) {
<ide> });
<ide> });
<ide> it('ensures Group model is created successfully', (done) => {
<del> models.Group.create(newGroup).then((createdGroup) => {
<del> expect(createdGroup.createdBy).toEqual('Jane Doe');
<add> models.Group.create(fixtures.newGroup2).then((createdGroup) => {
<add> expect(createdGroup.createdBy).toEqual('John Doe');
<ide> done();
<ide> });
<ide> }); |
|
Java | apache-2.0 | 01138b8e98fdfd7e1048690ebf2a4eec04e8d3e4 | 0 | karamelchef/karamel,karamelchef/karamel,karamelchef/karamel,karamelchef/karamel,karamelchef/karamel | package se.kth.karamel.webservice;
import icons.TrayUI;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.jetty.MutableServletContextHandler;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.eclipse.jetty.server.AbstractNetworkConnector;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import se.kth.karamel.backend.ClusterDefinitionService;
import se.kth.karamel.client.api.KaramelApi;
import se.kth.karamel.client.api.KaramelApiImpl;
import se.kth.karamel.common.CookbookScaffolder;
import se.kth.karamel.common.clusterdef.yaml.YamlCluster;
import se.kth.karamel.common.exception.KaramelException;
import se.kth.karamel.common.util.SshKeyPair;
import se.kth.karamel.webservice.calls.cluster.ProcessCommand;
import se.kth.karamel.webservice.calls.cluster.StartCluster;
import se.kth.karamel.webservice.calls.definition.FetchCookbook;
import se.kth.karamel.webservice.calls.definition.JsonToYaml;
import se.kth.karamel.webservice.calls.definition.YamlToJson;
import se.kth.karamel.webservice.calls.ec2.LoadEc2Credentials;
import se.kth.karamel.webservice.calls.ec2.ValidateEc2Credentials;
import se.kth.karamel.webservice.calls.experiment.LoadExperiment;
import se.kth.karamel.webservice.calls.experiment.PushExperiment;
import se.kth.karamel.webservice.calls.experiment.RemoveFileFromExperiment;
import se.kth.karamel.webservice.calls.gce.LoadGceCredentials;
import se.kth.karamel.webservice.calls.gce.ValidateGceCredentials;
import se.kth.karamel.webservice.calls.github.GetGithubCredentials;
import se.kth.karamel.webservice.calls.github.GetGithubOrgs;
import se.kth.karamel.webservice.calls.github.GetGithubRepos;
import se.kth.karamel.webservice.calls.github.RemoveRepository;
import se.kth.karamel.webservice.calls.github.SetGithubCredentials;
import se.kth.karamel.webservice.calls.nova.LoadNovaCredentials;
import se.kth.karamel.webservice.calls.nova.ValidateNovaCredentials;
import se.kth.karamel.webservice.calls.occi.LoadOcciCredentials;
import se.kth.karamel.webservice.calls.occi.ValidateOcciCredentials;
import se.kth.karamel.webservice.calls.sshkeys.GenerateSshKeys;
import se.kth.karamel.webservice.calls.sshkeys.LoadSshKeys;
import se.kth.karamel.webservice.calls.sshkeys.RegisterSshKeys;
import se.kth.karamel.webservice.calls.sshkeys.SetSudoPassword;
import se.kth.karamel.webservice.calls.system.ExitKaramel;
import se.kth.karamel.webservice.calls.system.PingServer;
import se.kth.karamel.webservice.utils.TemplateHealthCheck;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.swing.ImageIcon;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.SystemTray;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.EnumSet;
import static se.kth.karamel.common.CookbookScaffolder.deleteRecursive;
public class KaramelServiceApplication extends Application<KaramelServiceConfiguration> {
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(
KaramelServiceApplication.class);
private static KaramelApi karamelApi;
public static TrayUI trayUi;
private TemplateHealthCheck healthCheck;
private static final Options options = new Options();
private static final CommandLineParser parser = new GnuParser();
private static final int PORT = 58931;
private static ServerSocket s;
private static boolean cli = false;
private static boolean headless = false;
static {
// Ensure a single instance of the app is running
try {
s = new ServerSocket(PORT, 10, InetAddress.getLocalHost());
} catch (UnknownHostException e) {
// shouldn't happen for localhost
} catch (IOException e) {
// port taken, so app is already running
logger.info("An instance of Karamel is already running. Exiting...");
System.exit(10);
}
options.addOption("help", false, "Print help message.");
options.addOption(OptionBuilder.withArgName("yamlFile")
.hasArg()
.withDescription("Dropwizard configuration in a YAML file")
.create("server"));
options.addOption(OptionBuilder.withArgName("yamlFile")
.hasArg()
.withDescription("Karamel cluster definition in a YAML file")
.create("launch"));
options.addOption("scaffold", false, "Creates scaffolding for a new Chef/Karamel Cookbook.");
options.addOption("headless", false, "Launch Karamel from a headless server (no terminal on the server).");
}
public static void create() {
String name = "";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter cookbook name: ");
name = br.readLine();
File cb = new File("cookbooks" + File.separator + name);
if (cb.exists()) {
boolean wiped = false;
while (!wiped) {
System.out.print("Do you wan t to over-write the existing cookbook " + name + "? (y/n) ");
String overwrite = br.readLine();
if (overwrite.compareToIgnoreCase("n") == 0 || overwrite.compareToIgnoreCase("no") == 0) {
logger.info("Not over-writing. Exiting.");
System.exit(0);
}
if (overwrite.compareToIgnoreCase("y") == 0 || overwrite.compareToIgnoreCase("yes") == 0) {
deleteRecursive(cb);
wiped = true;
}
}
}
String pathToCb = CookbookScaffolder.create(name);
logger.info("New Cookbook is now located at: " + pathToCb);
System.exit(0);
} catch (IOException ex) {
logger.error("", ex);
System.exit(-1);
}
}
/**
* Usage instructions
*
* @param exitValue
*/
public static void usage(int exitValue) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("karamel", options);
System.exit(exitValue);
}
public static void main(String[] args) throws Exception {
System.setProperty("java.net.preferIPv4Stack", "true");
String yamlTxt;
// These args are sent to the Dropwizard app (thread)
String[] modifiedArgs = new String[2];
modifiedArgs[0] = "server";
karamelApi = new KaramelApiImpl();
try {
CommandLine line = parser.parse(options, args);
if (line.getOptions().length == 0) {
usage(0);
}
if (line.hasOption("help")) {
usage(0);
}
if (line.hasOption("scaffold")) {
create();
}
if (line.hasOption("server")) {
modifiedArgs[1] = line.getOptionValue("server");
}
if (line.hasOption("launch")) {
cli = true;
headless = true;
}
if (line.hasOption("headless")) {
headless = true;
}
if (cli) {
// Try to open and read the yaml file.
// Print error msg if invalid file or invalid YAML.
yamlTxt = CookbookScaffolder.readFile(line.getOptionValue("launch"));
YamlCluster cluster = ClusterDefinitionService.yamlToYamlObject(yamlTxt);
String jsonTxt = karamelApi.yamlToJson(yamlTxt);
SshKeyPair pair = karamelApi.loadSshKeysIfExist();
karamelApi.registerSshKeys(pair);
karamelApi.startCluster(jsonTxt);
long ms1 = System.currentTimeMillis();
while (ms1 + 6000000 > System.currentTimeMillis()) {
String clusterStatus = karamelApi.getClusterStatus(cluster.getName());
logger.debug(clusterStatus);
Thread.currentThread().sleep(30000);
}
}
} catch (ParseException e) {
usage(-1);
} catch (KaramelException e) {
System.err.println("Inalid yaml file; " + e.getMessage());
System.exit(-2);
}
if (!cli) {
new KaramelServiceApplication().run(modifiedArgs);
}
Runtime.getRuntime().addShutdownHook(new KaramelCleanupBeforeShutdownThread());
}
// Name of the application displayed when application boots up.
@Override
public String getName() {
return "karamel-core";
}
// Pre start of the dropwizard to plugin with separate bundles.
@Override
public void initialize(Bootstrap<KaramelServiceConfiguration> bootstrap) {
logger.debug("Executing any initialization tasks.");
// bootstrap.addBundle(new ConfiguredAssetsBundle("/assets/", "/dashboard/"));
// https://groups.google.com/forum/#!topic/dropwizard-user/UaVcAYm0VlQ
bootstrap.addBundle(new AssetsBundle("/assets/", "/"));
}
@Override
public void run(KaramelServiceConfiguration configuration, Environment environment) throws Exception {
healthCheck = new TemplateHealthCheck("%s");
// http://stackoverflow.com/questions/26610502/serve-static-content-from-a-base-url-in-dropwizard-0-7-1
// environment.jersey().setUrlPattern("/angular/*");
/*
* To allow cross orign resource request from angular js client
*/
FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class
);
// Allow cross origin requests.
filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class
), true, "/*");
filter.setInitParameter(
"allowedOrigins", "*"); // allowed origins comma separated
filter.setInitParameter(
"allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
filter.setInitParameter(
"allowedMethods", "GET,PUT,POST,DELETE,OPTIONS,HEAD");
filter.setInitParameter(
"preflightMaxAge", "5184000"); // 2 months
filter.setInitParameter(
"allowCredentials", "true");
environment.jersey()
.setUrlPattern("/api/*");
environment.healthChecks()
.register("template", healthCheck);
//definitions
environment.jersey().register(new YamlToJson(karamelApi));
environment.jersey().register(new JsonToYaml(karamelApi));
environment.jersey().register(new FetchCookbook(karamelApi));
//ssh
environment.jersey().register(new LoadSshKeys(karamelApi));
environment.jersey().register(new RegisterSshKeys(karamelApi));
environment.jersey().register(new GenerateSshKeys(karamelApi));
environment.jersey().register(new SetSudoPassword(karamelApi));
//ec2
environment.jersey().register(new LoadEc2Credentials(karamelApi));
environment.jersey().register(new ValidateEc2Credentials(karamelApi));
//gce
environment.jersey().register(new LoadGceCredentials(karamelApi));
environment.jersey().register(new ValidateGceCredentials(karamelApi));
//cluster
environment.jersey().register(new StartCluster(karamelApi));
environment.jersey().register(new ProcessCommand(karamelApi));
environment.jersey().register(new ExitKaramel(karamelApi));
environment.jersey().register(new PingServer(karamelApi));
//github
environment.jersey().register(new GetGithubCredentials(karamelApi));
environment.jersey().register(new SetGithubCredentials(karamelApi));
environment.jersey().register(new GetGithubOrgs(karamelApi));
environment.jersey().register(new GetGithubRepos(karamelApi));
environment.jersey().register(new RemoveRepository(karamelApi));
//experiment
environment.jersey().register(new LoadExperiment(karamelApi));
environment.jersey().register(new PushExperiment(karamelApi));
environment.jersey().register(new RemoveFileFromExperiment(karamelApi));
//Openstack nova
environment.jersey().register(new LoadNovaCredentials(karamelApi));
environment.jersey().register(new ValidateNovaCredentials(karamelApi));
//occi
environment.jersey().register(new LoadOcciCredentials(karamelApi));
environment.jersey().register(new ValidateOcciCredentials(karamelApi));
// Wait to make sure jersey/angularJS is running before launching the browser
final int webPort = getPort(environment);
if (!headless) {
if (SystemTray.isSupported()) {
trayUi = new TrayUI(createImage("if.png", "tray icon"), getPort(environment));
}
new Thread("webpage opening..") {
public void run() {
try {
Thread.sleep(1500);
openWebpage(new URL("http://localhost:" + webPort + "/index.html#/"));
} catch (InterruptedException e) {
// swallow the exception
} catch (java.net.MalformedURLException e) {
// swallow the exception
}
}
}.start();
}
}
protected static Image createImage(String path, String description) {
URL imageURL = TrayUI.class.getResource(path);
if (imageURL == null) {
System.err.println("Resource not found: " + path);
return null;
} else {
return (new ImageIcon(imageURL, description)).getImage();
}
}
public int getPort(Environment environment) {
int defaultPort = 9090;
MutableServletContextHandler h = environment.getApplicationContext();
if (h == null) {
return defaultPort;
}
Server s = h.getServer();
if (s == null) {
return defaultPort;
}
Connector[] c = s.getConnectors();
if (c != null && c.length > 0) {
AbstractNetworkConnector anc = (AbstractNetworkConnector) c[0];
if (anc != null) {
return anc.getLocalPort();
}
}
return defaultPort;
}
public synchronized static void openWebpage(URI uri) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(uri);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.err.println("Brower UI could not be launched using Java's Desktop library. "
+ "Are you running a window manager?");
System.err.println("If you are using Ubuntu, try: sudo apt-get install libgnome");
System.err.println("Retrying to launch the browser now using a different method.");
BareBonesBrowserLaunch.openURL(uri.toASCIIString());
}
}
public static void openWebpage(URL url) {
try {
openWebpage(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
static class KaramelCleanupBeforeShutdownThread extends Thread {
@Override
public void run() {
logger.info("Bye! Cleaning up first....");
// TODO - interrupt all threads
// Should we cleanup AMIs?
}
}
}
| karamel-ui/src/main/java/se/kth/karamel/webservice/KaramelServiceApplication.java | package se.kth.karamel.webservice;
import icons.TrayUI;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.jetty.MutableServletContextHandler;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.eclipse.jetty.server.AbstractNetworkConnector;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import se.kth.karamel.backend.ClusterDefinitionService;
import se.kth.karamel.client.api.KaramelApi;
import se.kth.karamel.client.api.KaramelApiImpl;
import se.kth.karamel.common.CookbookScaffolder;
import se.kth.karamel.common.clusterdef.yaml.YamlCluster;
import se.kth.karamel.common.exception.KaramelException;
import se.kth.karamel.webservice.calls.cluster.ProcessCommand;
import se.kth.karamel.webservice.calls.cluster.StartCluster;
import se.kth.karamel.webservice.calls.definition.FetchCookbook;
import se.kth.karamel.webservice.calls.definition.JsonToYaml;
import se.kth.karamel.webservice.calls.definition.YamlToJson;
import se.kth.karamel.webservice.calls.ec2.LoadEc2Credentials;
import se.kth.karamel.webservice.calls.ec2.ValidateEc2Credentials;
import se.kth.karamel.webservice.calls.experiment.LoadExperiment;
import se.kth.karamel.webservice.calls.experiment.PushExperiment;
import se.kth.karamel.webservice.calls.experiment.RemoveFileFromExperiment;
import se.kth.karamel.webservice.calls.gce.LoadGceCredentials;
import se.kth.karamel.webservice.calls.gce.ValidateGceCredentials;
import se.kth.karamel.webservice.calls.github.GetGithubCredentials;
import se.kth.karamel.webservice.calls.github.GetGithubOrgs;
import se.kth.karamel.webservice.calls.github.GetGithubRepos;
import se.kth.karamel.webservice.calls.github.RemoveRepository;
import se.kth.karamel.webservice.calls.github.SetGithubCredentials;
import se.kth.karamel.webservice.calls.nova.LoadNovaCredentials;
import se.kth.karamel.webservice.calls.nova.ValidateNovaCredentials;
import se.kth.karamel.webservice.calls.occi.LoadOcciCredentials;
import se.kth.karamel.webservice.calls.occi.ValidateOcciCredentials;
import se.kth.karamel.webservice.calls.sshkeys.GenerateSshKeys;
import se.kth.karamel.webservice.calls.sshkeys.LoadSshKeys;
import se.kth.karamel.webservice.calls.sshkeys.RegisterSshKeys;
import se.kth.karamel.webservice.calls.sshkeys.SetSudoPassword;
import se.kth.karamel.webservice.calls.system.ExitKaramel;
import se.kth.karamel.webservice.calls.system.PingServer;
import se.kth.karamel.webservice.utils.TemplateHealthCheck;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.swing.ImageIcon;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.SystemTray;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.EnumSet;
import static se.kth.karamel.common.CookbookScaffolder.deleteRecursive;
public class KaramelServiceApplication extends Application<KaramelServiceConfiguration> {
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(
KaramelServiceApplication.class);
private static KaramelApi karamelApi;
public static TrayUI trayUi;
private TemplateHealthCheck healthCheck;
private static final Options options = new Options();
private static final CommandLineParser parser = new GnuParser();
private static final int PORT = 58931;
private static ServerSocket s;
private static boolean cli = false;
private static boolean headless = false;
static {
// Ensure a single instance of the app is running
try {
s = new ServerSocket(PORT, 10, InetAddress.getLocalHost());
} catch (UnknownHostException e) {
// shouldn't happen for localhost
} catch (IOException e) {
// port taken, so app is already running
logger.info("An instance of Karamel is already running. Exiting...");
System.exit(10);
}
options.addOption("help", false, "Print help message.");
options.addOption(OptionBuilder.withArgName("yamlFile")
.hasArg()
.withDescription("Dropwizard configuration in a YAML file")
.create("server"));
options.addOption(OptionBuilder.withArgName("yamlFile")
.hasArg()
.withDescription("Karamel cluster definition in a YAML file")
.create("launch"));
options.addOption("scaffold", false, "Creates scaffolding for a new Chef/Karamel Cookbook.");
options.addOption("headless", false, "Launch Karamel from a headless server (no terminal on the server).");
}
public static void create() {
String name = "";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter cookbook name: ");
name = br.readLine();
File cb = new File("cookbooks" + File.separator + name);
if (cb.exists()) {
boolean wiped = false;
while (!wiped) {
System.out.print("Do you wan t to over-write the existing cookbook " + name + "? (y/n) ");
String overwrite = br.readLine();
if (overwrite.compareToIgnoreCase("n") == 0 || overwrite.compareToIgnoreCase("no") == 0) {
logger.info("Not over-writing. Exiting.");
System.exit(0);
}
if (overwrite.compareToIgnoreCase("y") == 0 || overwrite.compareToIgnoreCase("yes") == 0) {
deleteRecursive(cb);
wiped = true;
}
}
}
String pathToCb = CookbookScaffolder.create(name);
logger.info("New Cookbook is now located at: " + pathToCb);
System.exit(0);
} catch (IOException ex) {
logger.error("", ex);
System.exit(-1);
}
}
/**
* Usage instructions
*
* @param exitValue
*/
public static void usage(int exitValue) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("karamel", options);
System.exit(exitValue);
}
public static void main(String[] args) throws Exception {
System.setProperty("java.net.preferIPv4Stack", "true");
String yamlTxt;
// These args are sent to the Dropwizard app (thread)
String[] modifiedArgs = new String[2];
modifiedArgs[0] = "server";
karamelApi = new KaramelApiImpl();
try {
CommandLine line = parser.parse(options, args);
if (line.getOptions().length == 0) {
usage(0);
}
if (line.hasOption("help")) {
usage(0);
}
if (line.hasOption("scaffold")) {
create();
}
if (line.hasOption("server")) {
modifiedArgs[1] = line.getOptionValue("server");
}
if (line.hasOption("launch")) {
cli = true;
headless = true;
}
if (line.hasOption("headless")) {
headless = true;
}
if (cli) {
// Try to open and read the yaml file.
// Print error msg if invalid file or invalid YAML.
yamlTxt = CookbookScaffolder.readFile(line.getOptionValue("launch"));
YamlCluster cluster = ClusterDefinitionService.yamlToYamlObject(yamlTxt);
String jsonTxt = karamelApi.yamlToJson(yamlTxt);
karamelApi.loadSshKeysIfExist();
karamelApi.startCluster(jsonTxt);
long ms1 = System.currentTimeMillis();
while (ms1 + 6000000 > System.currentTimeMillis()) {
String clusterStatus = karamelApi.getClusterStatus(cluster.getName());
logger.debug(clusterStatus);
Thread.currentThread().sleep(30000);
}
}
} catch (ParseException e) {
usage(-1);
} catch (KaramelException e) {
System.err.println("Inalid yaml file; " + e.getMessage());
System.exit(-2);
}
if (!cli) {
new KaramelServiceApplication().run(modifiedArgs);
}
Runtime.getRuntime().addShutdownHook(new KaramelCleanupBeforeShutdownThread());
}
// Name of the application displayed when application boots up.
@Override
public String getName() {
return "karamel-core";
}
// Pre start of the dropwizard to plugin with separate bundles.
@Override
public void initialize(Bootstrap<KaramelServiceConfiguration> bootstrap) {
logger.debug("Executing any initialization tasks.");
// bootstrap.addBundle(new ConfiguredAssetsBundle("/assets/", "/dashboard/"));
// https://groups.google.com/forum/#!topic/dropwizard-user/UaVcAYm0VlQ
bootstrap.addBundle(new AssetsBundle("/assets/", "/"));
}
@Override
public void run(KaramelServiceConfiguration configuration, Environment environment) throws Exception {
healthCheck = new TemplateHealthCheck("%s");
// http://stackoverflow.com/questions/26610502/serve-static-content-from-a-base-url-in-dropwizard-0-7-1
// environment.jersey().setUrlPattern("/angular/*");
/*
* To allow cross orign resource request from angular js client
*/
FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class
);
// Allow cross origin requests.
filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class
), true, "/*");
filter.setInitParameter(
"allowedOrigins", "*"); // allowed origins comma separated
filter.setInitParameter(
"allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
filter.setInitParameter(
"allowedMethods", "GET,PUT,POST,DELETE,OPTIONS,HEAD");
filter.setInitParameter(
"preflightMaxAge", "5184000"); // 2 months
filter.setInitParameter(
"allowCredentials", "true");
environment.jersey()
.setUrlPattern("/api/*");
environment.healthChecks()
.register("template", healthCheck);
//definitions
environment.jersey().register(new YamlToJson(karamelApi));
environment.jersey().register(new JsonToYaml(karamelApi));
environment.jersey().register(new FetchCookbook(karamelApi));
//ssh
environment.jersey().register(new LoadSshKeys(karamelApi));
environment.jersey().register(new RegisterSshKeys(karamelApi));
environment.jersey().register(new GenerateSshKeys(karamelApi));
environment.jersey().register(new SetSudoPassword(karamelApi));
//ec2
environment.jersey().register(new LoadEc2Credentials(karamelApi));
environment.jersey().register(new ValidateEc2Credentials(karamelApi));
//gce
environment.jersey().register(new LoadGceCredentials(karamelApi));
environment.jersey().register(new ValidateGceCredentials(karamelApi));
//cluster
environment.jersey().register(new StartCluster(karamelApi));
environment.jersey().register(new ProcessCommand(karamelApi));
environment.jersey().register(new ExitKaramel(karamelApi));
environment.jersey().register(new PingServer(karamelApi));
//github
environment.jersey().register(new GetGithubCredentials(karamelApi));
environment.jersey().register(new SetGithubCredentials(karamelApi));
environment.jersey().register(new GetGithubOrgs(karamelApi));
environment.jersey().register(new GetGithubRepos(karamelApi));
environment.jersey().register(new RemoveRepository(karamelApi));
//experiment
environment.jersey().register(new LoadExperiment(karamelApi));
environment.jersey().register(new PushExperiment(karamelApi));
environment.jersey().register(new RemoveFileFromExperiment(karamelApi));
//Openstack nova
environment.jersey().register(new LoadNovaCredentials(karamelApi));
environment.jersey().register(new ValidateNovaCredentials(karamelApi));
//occi
environment.jersey().register(new LoadOcciCredentials(karamelApi));
environment.jersey().register(new ValidateOcciCredentials(karamelApi));
// Wait to make sure jersey/angularJS is running before launching the browser
final int webPort = getPort(environment);
if (!headless) {
if (SystemTray.isSupported()) {
trayUi = new TrayUI(createImage("if.png", "tray icon"), getPort(environment));
}
new Thread("webpage opening..") {
public void run() {
try {
Thread.sleep(1500);
openWebpage(new URL("http://localhost:" + webPort + "/index.html#/"));
} catch (InterruptedException e) {
// swallow the exception
} catch (java.net.MalformedURLException e) {
// swallow the exception
}
}
}.start();
}
}
protected static Image createImage(String path, String description) {
URL imageURL = TrayUI.class.getResource(path);
if (imageURL == null) {
System.err.println("Resource not found: " + path);
return null;
} else {
return (new ImageIcon(imageURL, description)).getImage();
}
}
public int getPort(Environment environment) {
int defaultPort = 9090;
MutableServletContextHandler h = environment.getApplicationContext();
if (h == null) {
return defaultPort;
}
Server s = h.getServer();
if (s == null) {
return defaultPort;
}
Connector[] c = s.getConnectors();
if (c != null && c.length > 0) {
AbstractNetworkConnector anc = (AbstractNetworkConnector) c[0];
if (anc != null) {
return anc.getLocalPort();
}
}
return defaultPort;
}
public synchronized static void openWebpage(URI uri) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(uri);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.err.println("Brower UI could not be launched using Java's Desktop library. "
+ "Are you running a window manager?");
System.err.println("If you are using Ubuntu, try: sudo apt-get install libgnome");
System.err.println("Retrying to launch the browser now using a different method.");
BareBonesBrowserLaunch.openURL(uri.toASCIIString());
}
}
public static void openWebpage(URL url) {
try {
openWebpage(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
static class KaramelCleanupBeforeShutdownThread extends Thread {
@Override
public void run() {
logger.info("Bye! Cleaning up first....");
// TODO - interrupt all threads
// Should we cleanup AMIs?
}
}
}
| Register ssh keys for commandline
| karamel-ui/src/main/java/se/kth/karamel/webservice/KaramelServiceApplication.java | Register ssh keys for commandline | <ide><path>aramel-ui/src/main/java/se/kth/karamel/webservice/KaramelServiceApplication.java
<ide> import se.kth.karamel.common.CookbookScaffolder;
<ide> import se.kth.karamel.common.clusterdef.yaml.YamlCluster;
<ide> import se.kth.karamel.common.exception.KaramelException;
<add>import se.kth.karamel.common.util.SshKeyPair;
<ide> import se.kth.karamel.webservice.calls.cluster.ProcessCommand;
<ide> import se.kth.karamel.webservice.calls.cluster.StartCluster;
<ide> import se.kth.karamel.webservice.calls.definition.FetchCookbook;
<ide> YamlCluster cluster = ClusterDefinitionService.yamlToYamlObject(yamlTxt);
<ide> String jsonTxt = karamelApi.yamlToJson(yamlTxt);
<ide>
<del> karamelApi.loadSshKeysIfExist();
<add> SshKeyPair pair = karamelApi.loadSshKeysIfExist();
<add> karamelApi.registerSshKeys(pair);
<ide>
<ide> karamelApi.startCluster(jsonTxt);
<ide> |
|
Java | apache-2.0 | 98bb530f9263f3bac0737971acc00dfef7ea4c35 | 0 | mixpanel/mixpanel-android,mixpanel/mixpanel-android,mixpanel/mixpanel-android | package com.mixpanel.android.mpmetrics;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.mixpanel.android.R;
import com.mixpanel.android.util.MPLog;
import com.mixpanel.android.util.ViewUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Attached to an Activity when you display a mini in-app notification.
*
* Users of the library should not reference this class directly.
*/
@TargetApi(MPConfig.UI_FEATURES_MIN_API)
@SuppressLint("ClickableViewAccessibility")
public class InAppFragment extends Fragment {
public void setDisplayState(final MixpanelAPI mixpanel, final int stateId, final UpdateDisplayState.DisplayState.InAppNotificationState displayState) {
// It would be better to pass in displayState to the only constructor, but
// Fragments require a default constructor that is called when Activities recreate them.
// This means that when the Activity recreates this Fragment (due to rotation, or
// the Activity going away and coming back), mDisplayStateId and mDisplayState are not
// initialized. Lifecycle methods should be aware of this case, and decline to show.
mMixpanel = mixpanel;
mDisplayStateId = stateId;
mDisplayState = displayState;
}
// It's safe to use onAttach(Activity) in API 23 as its implementation has not been changed.
// Bypass the Lint check for now.
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mParent = activity;
if (null == mDisplayState) {
cleanUp();
return;
}
// We have to manually clear these Runnables in onStop in case they exist, since they
// do illegal operations when onSaveInstanceState has been called already.
mHandler = new Handler();
mRemover = new Runnable() {
public void run() {
InAppFragment.this.remove();
}
};
mDisplayMini = new Runnable() {
@Override
public void run() {
mInAppView.setVisibility(View.VISIBLE);
mInAppView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
return InAppFragment.this.mDetector.onTouchEvent(event);
}
});
final ImageView notifImage = (ImageView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_image);
final float heightPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65, mParent.getResources().getDisplayMetrics());
final TranslateAnimation translate = new TranslateAnimation(0, 0, heightPx, 0);
translate.setInterpolator(new DecelerateInterpolator());
translate.setDuration(200);
mInAppView.startAnimation(translate);
final ScaleAnimation scale = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, heightPx / 2, heightPx / 2);
scale.setInterpolator(new SineBounceInterpolator());
scale.setDuration(400);
scale.setStartOffset(200);
notifImage.startAnimation(scale);
}
};
mDetector = new GestureDetector(activity, new GestureDetector.OnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
if (velocityY > 0) {
remove();
}
return true;
}
@Override
public void onLongPress(MotionEvent e) { }
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return false;
}
@Override
public void onShowPress(MotionEvent e) { }
@Override
public boolean onSingleTapUp(MotionEvent event) {
final MiniInAppNotification inApp = (MiniInAppNotification) mDisplayState.getInAppNotification();
JSONObject trackingProperties = null;
final String uriString = inApp.getCtaUrl();
if (uriString != null && uriString.length() > 0) {
Uri uri;
try {
uri = Uri.parse(uriString);
} catch (IllegalArgumentException e) {
MPLog.i(LOGTAG, "Can't parse notification URI, will not take any action", e);
return true;
}
try {
Intent viewIntent = new Intent(Intent.ACTION_VIEW, uri);
mParent.startActivity(viewIntent);
} catch (ActivityNotFoundException e) {
MPLog.i(LOGTAG, "User doesn't have an activity for notification URI " + uri);
}
try {
trackingProperties = new JSONObject();
trackingProperties.put("url", uriString);
} catch (final JSONException e) {
MPLog.e(LOGTAG, "Can't put url into json properties");
}
}
mMixpanel.getPeople().trackNotification("$campaign_open", inApp, trackingProperties);
remove();
return true;
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCleanedUp = false;
}
@SuppressWarnings("deprecation")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (null == mDisplayState) {
cleanUp();
} else {
mInAppView = inflater.inflate(R.layout.com_mixpanel_android_activity_notification_mini, container, false);
final TextView bodyTextView = (TextView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_title);
final ImageView notifImage = (ImageView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_image);
MiniInAppNotification inApp = (MiniInAppNotification) mDisplayState.getInAppNotification();
bodyTextView.setText(inApp.getBody());
bodyTextView.setTextColor(inApp.getBodyColor());
notifImage.setImageBitmap(inApp.getImage());
mHandler.postDelayed(mRemover, MINI_REMOVE_TIME);
GradientDrawable viewBackground = new GradientDrawable();
viewBackground.setColor(inApp.getBackgroundColor());
viewBackground.setCornerRadius(ViewUtils.dpToPx(7, getActivity()));
viewBackground.setStroke((int)ViewUtils.dpToPx(2, getActivity()), inApp.getBorderColor());
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mInAppView.setBackgroundDrawable(viewBackground);
} else {
mInAppView.setBackground(viewBackground);
}
Drawable myIcon = new BitmapDrawable(getResources(), mDisplayState.getInAppNotification().getImage());
myIcon.setColorFilter(inApp.getImageTintColor(), PorterDuff.Mode.SRC_ATOP);
notifImage.setImageDrawable(myIcon);
}
return mInAppView;
}
@Override
public void onStart() {
super.onStart();
if (mCleanedUp) {
mParent.getFragmentManager().beginTransaction().remove(this).commit();
}
}
@Override
public void onResume() {
super.onResume();
// getHighlightColorFromBackground doesn't seem to work on onResume because the view
// has not been fully rendered, so try and delay a little bit. This is also a bit better UX
// by giving the user some time to process the new Activity before displaying the notification.
mHandler.postDelayed(mDisplayMini, 500);
}
@Override
public void onSaveInstanceState(Bundle outState) {
cleanUp();
super.onSaveInstanceState(outState);
}
@Override
public void onPause() {
super.onPause();
cleanUp();
}
private void cleanUp() {
if (!mCleanedUp) {
mHandler.removeCallbacks(mRemover);
mHandler.removeCallbacks(mDisplayMini);
UpdateDisplayState.releaseDisplayState(mDisplayStateId);
final FragmentManager fragmentManager = mParent.getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.remove(this).commit();
}
mCleanedUp = true;
}
private void remove() {
boolean isDestroyed = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 ? mParent.isDestroyed() : false;
if (mParent != null && !mParent.isFinishing() && !isDestroyed && !mCleanedUp) {
mHandler.removeCallbacks(mRemover);
mHandler.removeCallbacks(mDisplayMini);
final FragmentManager fragmentManager = mParent.getFragmentManager();
// setCustomAnimations works on a per transaction level, so the animations set
// when this fragment was created do not apply
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(0, R.animator.com_mixpanel_android_slide_down).remove(this).commit();
UpdateDisplayState.releaseDisplayState(mDisplayStateId);
mCleanedUp = true;
}
}
private class SineBounceInterpolator implements Interpolator {
public SineBounceInterpolator() { }
public float getInterpolation(float t) {
return (float) -(Math.pow(Math.E, -8*t) * Math.cos(12*t)) + 1;
}
}
private MixpanelAPI mMixpanel;
private Activity mParent;
private GestureDetector mDetector;
private Handler mHandler;
private int mDisplayStateId;
private UpdateDisplayState.DisplayState.InAppNotificationState mDisplayState;
private Runnable mRemover, mDisplayMini;
private View mInAppView;
private boolean mCleanedUp;
private static final String LOGTAG = "MixpanelAPI.InAppFrag";
private static final int MINI_REMOVE_TIME = 10000;
}
| src/main/java/com/mixpanel/android/mpmetrics/InAppFragment.java | package com.mixpanel.android.mpmetrics;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.mixpanel.android.R;
import com.mixpanel.android.util.MPLog;
import com.mixpanel.android.util.ViewUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Attached to an Activity when you display a mini in-app notification.
*
* Users of the library should not reference this class directly.
*/
@TargetApi(MPConfig.UI_FEATURES_MIN_API)
@SuppressLint("ClickableViewAccessibility")
public class InAppFragment extends Fragment {
public void setDisplayState(final MixpanelAPI mixpanel, final int stateId, final UpdateDisplayState.DisplayState.InAppNotificationState displayState) {
// It would be better to pass in displayState to the only constructor, but
// Fragments require a default constructor that is called when Activities recreate them.
// This means that when the Activity recreates this Fragment (due to rotation, or
// the Activity going away and coming back), mDisplayStateId and mDisplayState are not
// initialized. Lifecycle methods should be aware of this case, and decline to show.
mMixpanel = mixpanel;
mDisplayStateId = stateId;
mDisplayState = displayState;
}
// It's safe to use onAttach(Activity) in API 23 as its implementation has not been changed.
// Bypass the Lint check for now.
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mParent = activity;
if (null == mDisplayState) {
cleanUp();
return;
}
// We have to manually clear these Runnables in onStop in case they exist, since they
// do illegal operations when onSaveInstanceState has been called already.
mHandler = new Handler();
mRemover = new Runnable() {
public void run() {
InAppFragment.this.remove();
}
};
mDisplayMini = new Runnable() {
@Override
public void run() {
mInAppView.setVisibility(View.VISIBLE);
mInAppView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
return InAppFragment.this.mDetector.onTouchEvent(event);
}
});
final ImageView notifImage = (ImageView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_image);
final float heightPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65, mParent.getResources().getDisplayMetrics());
final TranslateAnimation translate = new TranslateAnimation(0, 0, heightPx, 0);
translate.setInterpolator(new DecelerateInterpolator());
translate.setDuration(200);
mInAppView.startAnimation(translate);
final ScaleAnimation scale = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, heightPx / 2, heightPx / 2);
scale.setInterpolator(new SineBounceInterpolator());
scale.setDuration(400);
scale.setStartOffset(200);
notifImage.startAnimation(scale);
}
};
mDetector = new GestureDetector(activity, new GestureDetector.OnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
if (velocityY > 0) {
remove();
}
return true;
}
@Override
public void onLongPress(MotionEvent e) { }
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return false;
}
@Override
public void onShowPress(MotionEvent e) { }
@Override
public boolean onSingleTapUp(MotionEvent event) {
final MiniInAppNotification inApp = (MiniInAppNotification) mDisplayState.getInAppNotification();
JSONObject trackingProperties = null;
final String uriString = inApp.getCtaUrl();
if (uriString != null && uriString.length() > 0) {
Uri uri;
try {
uri = Uri.parse(uriString);
} catch (IllegalArgumentException e) {
MPLog.i(LOGTAG, "Can't parse notification URI, will not take any action", e);
return true;
}
try {
Intent viewIntent = new Intent(Intent.ACTION_VIEW, uri);
mParent.startActivity(viewIntent);
} catch (ActivityNotFoundException e) {
MPLog.i(LOGTAG, "User doesn't have an activity for notification URI " + uri);
}
try {
trackingProperties = new JSONObject();
trackingProperties.put("url", uriString);
} catch (final JSONException e) {
MPLog.e(LOGTAG, "Can't put url into json properties");
}
}
mMixpanel.getPeople().trackNotification("$campaign_open", inApp, trackingProperties);
remove();
return true;
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCleanedUp = false;
}
@SuppressWarnings("deprecation")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (null == mDisplayState) {
cleanUp();
} else {
mInAppView = inflater.inflate(R.layout.com_mixpanel_android_activity_notification_mini, container, false);
final TextView bodyTextView = (TextView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_title);
final ImageView notifImage = (ImageView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_image);
MiniInAppNotification inApp = (MiniInAppNotification) mDisplayState.getInAppNotification();
bodyTextView.setText(inApp.getBody());
bodyTextView.setTextColor(inApp.getBodyColor());
notifImage.setImageBitmap(inApp.getImage());
mHandler.postDelayed(mRemover, MINI_REMOVE_TIME);
GradientDrawable viewBackground = new GradientDrawable();
viewBackground.setColor(inApp.getBackgroundColor());
viewBackground.setCornerRadius(ViewUtils.dpToPx(7, getActivity()));
viewBackground.setStroke((int)ViewUtils.dpToPx(2, getActivity()), inApp.getBorderColor());
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mInAppView.setBackgroundDrawable(viewBackground);
} else {
mInAppView.setBackground(viewBackground);
}
Drawable myIcon = new BitmapDrawable(getResources(), mDisplayState.getInAppNotification().getImage());
myIcon.setColorFilter(inApp.getImageTintColor(), PorterDuff.Mode.SRC_ATOP);
notifImage.setImageDrawable(myIcon);
}
return mInAppView;
}
@Override
public void onStart() {
super.onStart();
if (mCleanedUp) {
mParent.getFragmentManager().beginTransaction().remove(this).commit();
}
}
@Override
public void onResume() {
super.onResume();
// getHighlightColorFromBackground doesn't seem to work on onResume because the view
// has not been fully rendered, so try and delay a little bit. This is also a bit better UX
// by giving the user some time to process the new Activity before displaying the notification.
mHandler.postDelayed(mDisplayMini, 500);
}
@Override
public void onSaveInstanceState(Bundle outState) {
cleanUp();
super.onSaveInstanceState(outState);
}
@Override
public void onPause() {
super.onPause();
cleanUp();
}
private void cleanUp() {
if (!mCleanedUp) {
mHandler.removeCallbacks(mRemover);
mHandler.removeCallbacks(mDisplayMini);
UpdateDisplayState.releaseDisplayState(mDisplayStateId);
final FragmentManager fragmentManager = mParent.getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.remove(this).commit();
}
mCleanedUp = true;
}
private void remove() {
if (mParent != null && !mCleanedUp) {
mHandler.removeCallbacks(mRemover);
mHandler.removeCallbacks(mDisplayMini);
final FragmentManager fragmentManager = mParent.getFragmentManager();
// setCustomAnimations works on a per transaction level, so the animations set
// when this fragment was created do not apply
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(0, R.animator.com_mixpanel_android_slide_down).remove(this).commit();
UpdateDisplayState.releaseDisplayState(mDisplayStateId);
mCleanedUp = true;
}
}
private class SineBounceInterpolator implements Interpolator {
public SineBounceInterpolator() { }
public float getInterpolation(float t) {
return (float) -(Math.pow(Math.E, -8*t) * Math.cos(12*t)) + 1;
}
}
private MixpanelAPI mMixpanel;
private Activity mParent;
private GestureDetector mDetector;
private Handler mHandler;
private int mDisplayStateId;
private UpdateDisplayState.DisplayState.InAppNotificationState mDisplayState;
private Runnable mRemover, mDisplayMini;
private View mInAppView;
private boolean mCleanedUp;
private static final String LOGTAG = "MixpanelAPI.InAppFrag";
private static final int MINI_REMOVE_TIME = 10000;
}
| Fix crash when committing transaction while activity is being destroyed
| src/main/java/com/mixpanel/android/mpmetrics/InAppFragment.java | Fix crash when committing transaction while activity is being destroyed | <ide><path>rc/main/java/com/mixpanel/android/mpmetrics/InAppFragment.java
<ide> }
<ide>
<ide> private void remove() {
<del> if (mParent != null && !mCleanedUp) {
<add> boolean isDestroyed = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 ? mParent.isDestroyed() : false;
<add> if (mParent != null && !mParent.isFinishing() && !isDestroyed && !mCleanedUp) {
<ide> mHandler.removeCallbacks(mRemover);
<ide> mHandler.removeCallbacks(mDisplayMini);
<ide> |
|
Java | apache-2.0 | 55546da069c982fb17819be1ccb275626f8c8133 | 0 | javamelody/javamelody,javamelody/javamelody,javamelody/javamelody | /*
* Copyright 2008-2012 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Java Melody 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 3 of the License, or
* (at your option) any later version.
*
* Java Melody 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 Java Melody. If not, see <http://www.gnu.org/licenses/>.
*/
package net.bull.javamelody;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
/**
* Classe permettant d'ouvrir une connexion http et de récupérer les objets java sérialisés dans la réponse.
* Utilisée dans le serveur de collecte.
* @author Emeric Vernat
*/
class LabradorRetriever {
@SuppressWarnings("all")
private static final Logger LOGGER = Logger.getLogger("javamelody");
/** Timeout des connections serveur en millisecondes (0 : pas de timeout). */
private static final int CONNECTION_TIMEOUT = 20000;
/** Timeout de lecture des connections serveur en millisecondes (0 : pas de timeout). */
private static final int READ_TIMEOUT = 60000;
private final URL url;
private final Map<String, String> headers;
// Rq: les configurations suivantes sont celles par défaut, on ne les change pas
// static { HttpURLConnection.setFollowRedirects(true);
// URLConnection.setDefaultAllowUserInteraction(true); }
private static class CounterInputStream extends InputStream {
private final InputStream inputStream;
private int dataLength;
CounterInputStream(InputStream inputStream) {
super();
this.inputStream = inputStream;
}
int getDataLength() {
return dataLength;
}
@Override
public int read() throws IOException {
final int result = inputStream.read();
if (result != -1) {
dataLength += 1;
}
return result;
}
@Override
public int read(byte[] bytes) throws IOException {
final int result = inputStream.read(bytes);
if (result != -1) {
dataLength += result;
}
return result;
}
@Override
public int read(byte[] bytes, int off, int len) throws IOException {
final int result = inputStream.read(bytes, off, len);
if (result != -1) {
dataLength += result;
}
return result;
}
@Override
public long skip(long n) throws IOException {
return inputStream.skip(n);
}
@Override
public int available() throws IOException {
return inputStream.available();
}
@Override
public void close() throws IOException {
inputStream.close();
}
@Override
public boolean markSupported() {
return false; // Assume that mark is NO good for a counterInputStream
}
}
LabradorRetriever(URL url) {
this(url, null);
}
LabradorRetriever(URL url, Map<String, String> headers) {
super();
assert url != null;
this.url = url;
this.headers = headers;
}
<T> T call() throws IOException {
if (shouldMock()) {
// ce générique doit être conservé pour la compilation javac en intégration continue
return this.<T> createMockResultOfCall();
}
final long start = System.currentTimeMillis();
int dataLength = -1;
try {
final URLConnection connection = openConnection(url, headers);
// pour traductions (si on vient de CollectorServlet.forwardActionAndUpdateData,
// cela permet d'avoir les messages dans la bonne langue)
connection.setRequestProperty("Accept-Language", I18N.getCurrentLocale().getLanguage());
if (url.getUserInfo() != null) {
final String authorization = Base64Coder.encodeString(url.getUserInfo());
connection.setRequestProperty("Authorization", "Basic " + authorization);
}
// Rq: on ne gère pas pour l'instant les éventuels cookie de session http,
// puisque le filtre de monitoring n'est pas censé créer des sessions
// if (cookie != null) { connection.setRequestProperty("Cookie", cookie); }
connection.connect();
// final String setCookie = connection.getHeaderField("Set-Cookie");
// if (setCookie != null) { cookie = setCookie; }
final CounterInputStream counterInputStream = new CounterInputStream(
connection.getInputStream());
final T result;
try {
@SuppressWarnings("unchecked")
final T tmp = (T) read(connection, counterInputStream);
result = tmp;
} finally {
dataLength = counterInputStream.getDataLength();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("read on " + url + " : " + result);
}
if (result instanceof RuntimeException) {
throw (RuntimeException) result;
} else if (result instanceof Error) {
throw (Error) result;
} else if (result instanceof IOException) {
throw (IOException) result;
} else if (result instanceof Exception) {
throw createIOException((Exception) result);
}
return result;
} catch (final ClassNotFoundException e) {
throw createIOException(e);
} finally {
LOGGER.info("http call done in " + (System.currentTimeMillis() - start) + " ms with "
+ dataLength / 1024 + " KB read for " + url);
}
}
private static IOException createIOException(Exception e) {
// Rq: le constructeur de IOException avec message et cause n'existe qu'en jdk 1.6
final IOException ex = new IOException(e.getMessage());
ex.initCause(e);
return ex;
}
void copyTo(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
throws IOException {
if (shouldMock()) {
return;
}
assert httpRequest != null;
assert httpResponse != null;
final long start = System.currentTimeMillis();
int dataLength = -1;
try {
final URLConnection connection = openConnection(url, headers);
// pour traductions
connection.setRequestProperty("Accept-Language",
httpRequest.getHeader("Accept-Language"));
if (url.getUserInfo() != null) {
final String authorization = Base64Coder.encodeString(url.getUserInfo());
connection.setRequestProperty("Authorization", "Basic " + authorization);
}
// Rq: on ne gère pas pour l'instant les éventuels cookie de session http,
// puisque le filtre de monitoring n'est pas censé créer des sessions
// if (cookie != null) { connection.setRequestProperty("Cookie", cookie); }
connection.connect();
final CounterInputStream counterInputStream = new CounterInputStream(
connection.getInputStream());
InputStream input = counterInputStream;
try {
if ("gzip".equals(connection.getContentEncoding())) {
input = new GZIPInputStream(input);
}
httpResponse.setContentType(connection.getContentType());
TransportFormat.pump(input, httpResponse.getOutputStream());
} finally {
close(connection);
dataLength = counterInputStream.getDataLength();
}
} finally {
LOGGER.info("http call done in " + (System.currentTimeMillis() - start) + " ms with "
+ dataLength / 1024 + " KB read for " + url);
}
}
/**
* Ouvre la connection http.
* @param url URL
* @param headers Entêtes http
* @return Object
* @throws IOException Exception de communication
*/
private static URLConnection openConnection(URL url, Map<String, String> headers)
throws IOException {
final URLConnection connection = url.openConnection();
connection.setUseCaches(false);
if (CONNECTION_TIMEOUT > 0) {
connection.setConnectTimeout(CONNECTION_TIMEOUT);
}
if (READ_TIMEOUT > 0) {
connection.setReadTimeout(READ_TIMEOUT);
}
// grâce à cette propriété, l'application retournera un flux compressé si la taille
// dépasse x Ko
connection.setRequestProperty("Accept-Encoding", "gzip");
if (headers != null) {
for (final Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
return connection;
}
/**
* Lit l'objet renvoyé dans le flux de réponse.
* @return Object
* @param connection URLConnection
* @param inputStream InputStream à utiliser à la place de connection.getInputStream()
* @throws IOException Exception de communication
* @throws ClassNotFoundException Une classe transmise par le serveur n'a pas été trouvée
*/
private static Serializable read(URLConnection connection, InputStream inputStream)
throws IOException, ClassNotFoundException {
InputStream input = inputStream;
try {
if ("gzip".equals(connection.getContentEncoding())) {
// si la taille du flux dépasse x Ko et que l'application a retourné un flux compressé
// alors on le décompresse
input = new GZIPInputStream(input);
}
final String contentType = connection.getContentType();
final TransportFormat transportFormat;
if (contentType != null && contentType.startsWith("text/xml")) {
transportFormat = TransportFormat.XML;
} else {
transportFormat = TransportFormat.SERIALIZED;
}
return transportFormat.readSerializableFrom(input);
} finally {
close(connection);
}
}
private static void close(URLConnection connection) throws IOException {
// ce close doit être fait en finally
// (http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html)
connection.getInputStream().close();
if (connection instanceof HttpURLConnection) {
final InputStream error = ((HttpURLConnection) connection).getErrorStream();
if (error != null) {
error.close();
}
}
}
private static boolean shouldMock() {
return Boolean.parseBoolean(System.getProperty(Parameters.PARAMETER_SYSTEM_PREFIX
+ "mockLabradorRetriever"));
}
// bouchon pour tests unitaires
@SuppressWarnings("unchecked")
private <T> T createMockResultOfCall() throws IOException {
final Object result;
final String request = url.toString();
if (!request.contains(HttpParameters.PART_PARAMETER + '=')) {
final String message = request.contains("/test2") ? null
: "ceci est message pour le rapport";
result = Arrays.asList(new Counter(Counter.HTTP_COUNTER_NAME, null), new Counter(
"services", null), new Counter(Counter.ERROR_COUNTER_NAME, null),
new JavaInformations(null, true), message);
} else {
result = createMockResultOfPartCall(request);
}
return (T) result;
}
private Object createMockResultOfPartCall(String request) throws IOException {
final Object result;
if (request.contains(HttpParameters.SESSIONS_PART)
&& request.contains(HttpParameters.SESSION_ID_PARAMETER)) {
result = null;
} else if (request.contains(HttpParameters.SESSIONS_PART)
|| request.contains(HttpParameters.PROCESSES_PART)
|| request.contains(HttpParameters.CONNECTIONS_PART)) {
result = Collections.emptyList();
} else if (request.contains(HttpParameters.DATABASE_PART)) {
try {
result = new DatabaseInformations(0);
} catch (final Exception e) {
throw new IllegalStateException(e);
}
} else if (request.contains(HttpParameters.HEAP_HISTO_PART)) {
final InputStream input = getClass().getResourceAsStream("/heaphisto.txt");
try {
result = new HeapHistogram(input, false);
} finally {
input.close();
}
} else {
result = null;
}
return result;
}
}
| javamelody-core/src/main/java/net/bull/javamelody/LabradorRetriever.java | /*
* Copyright 2008-2012 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Java Melody 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 3 of the License, or
* (at your option) any later version.
*
* Java Melody 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 Java Melody. If not, see <http://www.gnu.org/licenses/>.
*/
package net.bull.javamelody;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
/**
* Classe permettant d'ouvrir une connexion http et de récupérer les objets java sérialisés dans la réponse.
* Utilisée dans le serveur de collecte.
* @author Emeric Vernat
*/
class LabradorRetriever {
@SuppressWarnings("all")
private static final Logger LOGGER = Logger.getLogger("javamelody");
/** Timeout des connections serveur en millisecondes (0 : pas de timeout). */
private static final int CONNECTION_TIMEOUT = 20000;
/** Timeout de lecture des connections serveur en millisecondes (0 : pas de timeout). */
private static final int READ_TIMEOUT = 60000;
private final URL url;
private final Map<String, String> headers;
// Rq: les configurations suivantes sont celles par défaut, on ne les change pas
// static { HttpURLConnection.setFollowRedirects(true);
// URLConnection.setDefaultAllowUserInteraction(true); }
private static class CounterInputStream extends InputStream {
private final InputStream inputStream;
private int dataLength;
CounterInputStream(InputStream inputStream) {
super();
this.inputStream = inputStream;
}
int getDataLength() {
return dataLength;
}
@Override
public int read() throws IOException {
final int result = inputStream.read();
if (result != -1) {
dataLength += 1;
}
return result;
}
@Override
public int read(byte[] bytes) throws IOException {
final int result = inputStream.read(bytes);
if (result != -1) {
dataLength += result;
}
return result;
}
@Override
public int read(byte[] bytes, int off, int len) throws IOException {
final int result = inputStream.read(bytes, off, len);
if (result != -1) {
dataLength += result;
}
return result;
}
@Override
public long skip(long n) throws IOException {
return inputStream.skip(n);
}
@Override
public int available() throws IOException {
return inputStream.available();
}
@Override
public void close() throws IOException {
inputStream.close();
}
@Override
public boolean markSupported() {
return false; // Assume that mark is NO good for a counterInputStream
}
}
LabradorRetriever(URL url) {
this(url, null);
}
LabradorRetriever(URL url, Map<String, String> headers) {
super();
assert url != null;
this.url = url;
this.headers = headers;
}
<T> T call() throws IOException {
if (shouldMock()) {
// ce générique doit être conservé pour la compilation javac en intégration continue
return this.<T> createMockResultOfCall();
}
final long start = System.currentTimeMillis();
int dataLength = -1;
try {
final URLConnection connection = openConnection(url, headers);
// pour traductions (si on vient de CollectorServlet.forwardActionAndUpdateData,
// cela permet d'avoir les messages dans la bonne langue)
connection.setRequestProperty("Accept-Language", I18N.getCurrentLocale().getLanguage());
if (url.getUserInfo() != null) {
final String authorization = Base64Coder.encodeString(url.getUserInfo());
connection.setRequestProperty("Authorization", "Basic " + authorization);
}
// Rq: on ne gère pas pour l'instant les éventuels cookie de session http,
// puisque le filtre de monitoring n'est pas censé créer des sessions
// if (cookie != null) { connection.setRequestProperty("Cookie", cookie); }
connection.connect();
// final String setCookie = connection.getHeaderField("Set-Cookie");
// if (setCookie != null) { cookie = setCookie; }
final CounterInputStream counterInputStream = new CounterInputStream(
connection.getInputStream());
final T result;
try {
@SuppressWarnings("unchecked")
final T tmp = (T) read(connection, counterInputStream);
result = tmp;
} finally {
dataLength = counterInputStream.getDataLength();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("read on " + url + " : " + result);
}
if (result instanceof RuntimeException) {
throw (RuntimeException) result;
} else if (result instanceof Error) {
throw (Error) result;
} else if (result instanceof IOException) {
throw (IOException) result;
} else if (result instanceof Exception) {
throw createIOException((Exception) result);
}
return result;
} catch (final ClassNotFoundException e) {
throw createIOException(e);
} finally {
LOGGER.info("http call done in " + (System.currentTimeMillis() - start) + " ms with "
+ dataLength / 1024 + " KB read for " + url);
}
}
private static IOException createIOException(Exception e) {
// Rq: le constructeur de IOException avec message et cause n'existe qu'en jdk 1.6
final IOException ex = new IOException(e.getMessage());
ex.initCause(e);
return ex;
}
void copyTo(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
throws IOException {
if (shouldMock()) {
return;
}
assert httpRequest != null;
assert httpResponse != null;
final long start = System.currentTimeMillis();
int dataLength = -1;
try {
final URLConnection connection = openConnection(url, headers);
// pour traductions
connection.setRequestProperty("Accept-Language",
httpRequest.getHeader("Accept-Language"));
if (url.getUserInfo() != null) {
final String authorization = Base64Coder.encodeString(url.getUserInfo());
connection.setRequestProperty("Authorization", "Basic " + authorization);
}
// Rq: on ne gère pas pour l'instant les éventuels cookie de session http,
// puisque le filtre de monitoring n'est pas censé créer des sessions
// if (cookie != null) { connection.setRequestProperty("Cookie", cookie); }
connection.connect();
final CounterInputStream counterInputStream = new CounterInputStream(
connection.getInputStream());
InputStream input = counterInputStream;
try {
if ("gzip".equals(connection.getContentEncoding())) {
input = new GZIPInputStream(input);
}
httpResponse.setContentType(connection.getContentType());
TransportFormat.pump(input, httpResponse.getOutputStream());
} finally {
close(connection);
dataLength = counterInputStream.getDataLength();
}
} finally {
LOGGER.info("http call done in " + (System.currentTimeMillis() - start) + " ms with "
+ dataLength / 1024 + " KB read for " + url);
}
}
/**
* Ouvre la connection http.
* @param url URL
* @param headers Entêtes http
* @return Object
* @throws IOException Exception de communication
*/
private static URLConnection openConnection(URL url, Map<String, String> headers)
throws IOException {
final URLConnection connection = url.openConnection();
connection.setUseCaches(false);
if (CONNECTION_TIMEOUT > 0) {
connection.setConnectTimeout(CONNECTION_TIMEOUT);
}
if (READ_TIMEOUT > 0) {
connection.setReadTimeout(READ_TIMEOUT);
}
// grâce à cette propriété, l'application retournera un flux compressé si la taille
// dépasse x Ko
connection.setRequestProperty("Accept-Encoding", "gzip");
if (headers != null) {
for (final Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
return connection;
}
/**
* Lit l'objet renvoyé dans le flux de réponse.
* @return Object
* @param connection URLConnection
* @param inputStream InputStream à utiliser à la place de connection.getInputStream()
* @throws IOException Exception de communication
* @throws ClassNotFoundException Une classe transmise par le serveur n'a pas été trouvée
*/
private static Serializable read(URLConnection connection, InputStream inputStream)
throws IOException, ClassNotFoundException {
InputStream input = inputStream;
try {
if ("gzip".equals(connection.getContentEncoding())) {
// si la taille du flux dépasse x Ko et que l'application a retourné un flux compressé
// alors on le décompresse
input = new GZIPInputStream(input);
}
final String contentType = connection.getContentType();
final TransportFormat transportFormat;
if (contentType != null && contentType.startsWith("text/xml")) {
transportFormat = TransportFormat.XML;
} else {
transportFormat = TransportFormat.SERIALIZED;
}
return transportFormat.readSerializableFrom(input);
} finally {
close(connection);
}
}
private static void close(URLConnection connection) throws IOException {
// ce close doit être fait en finally
// (http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html)
connection.getInputStream().close();
if (connection instanceof HttpURLConnection) {
final InputStream error = ((HttpURLConnection) connection).getErrorStream();
if (error != null) {
error.close();
}
}
}
private static boolean shouldMock() {
return Boolean.parseBoolean(System.getProperty(Parameters.PARAMETER_SYSTEM_PREFIX
+ "mockLabradorRetriever"));
}
// bouchon pour tests unitaires
@SuppressWarnings("unchecked")
private <T> T createMockResultOfCall() throws IOException {
final Object result;
final String request = url.toString();
if (!request.contains(HttpParameters.PART_PARAMETER + '=')) {
final String message = request.contains("/test2") ? null
: "ceci est message pour le rapport";
result = Arrays.asList(new Counter(Counter.HTTP_COUNTER_NAME, null), new Counter(
"services", null), new Counter(Counter.ERROR_COUNTER_NAME, null),
new JavaInformations(null, true), message);
} else {
result = createMockResultOfPartCall(request);
}
return (T) result;
}
private Object createMockResultOfPartCall(String request) throws IOException {
final Object result;
if (request.contains(HttpParameters.SESSIONS_PART)
&& request.contains(HttpParameters.SESSION_ID_PARAMETER)) {
result = null;
} else if (request.contains(HttpParameters.SESSIONS_PART)
|| request.contains(HttpParameters.PROCESSES_PART)
|| request.contains(HttpParameters.CONNECTIONS_PART)) {
result = Collections.emptyList();
} else if (request.contains(HttpParameters.DATABASE_PART)) {
try {
result = new DatabaseInformations(0);
} catch (final Exception e) {
throw new IllegalStateException(e);
}
} else if (request.contains(HttpParameters.HEAP_HISTO_PART)) {
final InputStream input = getClass().getResourceAsStream("/heaphisto.txt");
try {
result = new HeapHistogram(input, false);
} finally {
input.close();
}
} else {
result = null;
}
return result;
}
}
| clean-up | javamelody-core/src/main/java/net/bull/javamelody/LabradorRetriever.java | clean-up | <ide><path>avamelody-core/src/main/java/net/bull/javamelody/LabradorRetriever.java
<ide> * Lit l'objet renvoyé dans le flux de réponse.
<ide> * @return Object
<ide> * @param connection URLConnection
<del> * @param inputStream InputStream à utiliser à la place de connection.getInputStream()
<add> * @param inputStream InputStream à utiliser à la place de connection.getInputStream()
<ide> * @throws IOException Exception de communication
<ide> * @throws ClassNotFoundException Une classe transmise par le serveur n'a pas été trouvée
<ide> */ |
|
Java | agpl-3.0 | 7a551217cf3f4a0132c834acfeac1d6565376f58 | 0 | MusesProject/MusesServer,MusesProject/MusesServer | /*
* version 1.0 - MUSES prototype software
* Copyright MUSES project (European Commission FP7) - 2013
*
*/
package eu.musesproject.server.dataminer;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
/*
* #%L
* MUSES Server
* %%
* Copyright (C) 2013 - 2014 UGR
* %%
* 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 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/>.
* #L%
*/
/**
* The Class ParsingUtils.
*
* @author Paloma de las Cuevas (UGR)
* @version June 8, 2015
*/
public class ParsingUtils {
private Logger logger = Logger.getLogger(DataMiner.class);
public ParsingUtils() {
// TODO Auto-generated constructor stub
}
/**
* Method classifierParser in which weka classifier rules are parsed for the extraction of their
* conditions and classes (label applied to patterns which have been classified by that rule)
*
* @param classifierRules Rules obtained by the classifier
*
* @return ruleList List of rules in a format that can be compared to the existing set of rules
*/
public List<String> classifierParser(String classifierRules){
List<String> ruleList = new ArrayList<String>();
String ruleJRip = "\\((\\w+)([\\s\\>\\=\\<]+)([\\w\\.]+)\\)";
String labelJRip = "\\=\\>\\s\\w+\\=(\\w+)";
String rulePART = "(\\w+)([\\s\\>\\=\\<]+)(\\w+)\\s?(AND|\\:)?\\s?(\\w*)";
String ruleJ48 = "\\|*\\s*(\\w+)([\\s\\>\\=\\<]+)(\\w+)\\s?\\:?\\s?(\\w*)";
String ruleREPTree = "";
String lines[] = classifierRules.split("\\r?\\n");
int i = 0;
if (lines[0].contains("JRIP")) {
Pattern JRipPattern = Pattern.compile(ruleJRip);
Pattern JRipLabelPattern = Pattern.compile(labelJRip);
for (i = 1; i < lines.length; i++) {
Matcher JRipMatcher = JRipPattern.matcher(lines[i]);
Matcher JRipLabelMatcher = JRipLabelPattern.matcher(lines[i]);
while (JRipMatcher.find()) {
// Attribute name
JRipMatcher.group(1);
/* Relationship, JRipMatcher.group(2) can be =, <, <=, >, >= */
JRipMatcher.group(2);
// Value
JRipMatcher.group(3);
}
if (JRipLabelMatcher.find()) {
// Label
JRipLabelMatcher.group(1);
}
}
}
if (lines[0].contains("PART")) {
Pattern PARTPattern = Pattern.compile(rulePART);
for (i = 1; i < lines.length; i++) {
Matcher PARTMatcher = PARTPattern.matcher(lines[i]);
while (PARTMatcher.find()) {
// Attribute name
PARTMatcher.group(1);
/* Relationship, PARTMatcher.group(2) can be =, <, <=, >, >= */
PARTMatcher.group(2);
// Value
PARTMatcher.group(3);
if (!PARTMatcher.group(5).isEmpty()) {
// Label
PARTMatcher.group(5);
}
}
}
}
if (lines[0].contains("J48")) {
Pattern J48Pattern = Pattern.compile(ruleJ48);
for (i = 1; i < lines.length; i++) {
Matcher J48Matcher = J48Pattern.matcher(lines[i]);
while (J48Matcher.find()) {
logger.info(J48Matcher.group(1));
logger.info(J48Matcher.group(2));
logger.info(J48Matcher.group(3));
// Attribute name
J48Matcher.group(1);
/* Relationship, PARTMatcher.group(2) can be =, <, <=, >, >= */
J48Matcher.group(2);
// Value
J48Matcher.group(3);
if (!J48Matcher.group(4).isEmpty()) {
logger.info(J48Matcher.group(4));
// Label
J48Matcher.group(4);
}
}
}
}
if (lines[0].contains("REPTree")) {
}
return ruleList;
}
}
| src/main/java/eu/musesproject/server/dataminer/ParsingUtils.java | /*
* version 1.0 - MUSES prototype software
* Copyright MUSES project (European Commission FP7) - 2013
*
*/
package eu.musesproject.server.dataminer;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
/*
* #%L
* MUSES Server
* %%
* Copyright (C) 2013 - 2014 UGR
* %%
* 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 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/>.
* #L%
*/
/**
* The Class ParsingUtils.
*
* @author Paloma de las Cuevas (UGR)
* @version June 8, 2015
*/
public class ParsingUtils {
private Logger logger = Logger.getLogger(DataMiner.class);
public ParsingUtils() {
// TODO Auto-generated constructor stub
}
/**
* Method classifierParser in which weka classifier rules are parsed for the extraction of their
* conditions and classes (label applied to patterns which have been classified by that rule)
*
* @param classifierRules Rules obtained by the classifier
*
* @return ruleList List of rules in a format that can be compared to the existing set of rules
*/
public List<String> classifierParser(String classifierRules){
List<String> ruleList = new ArrayList<String>();
String ruleJRip = "\\((\\w+)([\\s\\>\\=\\<]+)([\\w\\.]+)\\)";
String labelJRip = "\\=\\>\\s\\w+\\=(\\w+)";
String rulePART = "(\\w+)([\\s\\>\\=\\<]+)(\\w+)\\s?(AND|\\:)?\\s?(\\w*)";
String ruleJ48 = "";
String ruleREPTree = "";
String lines[] = classifierRules.split("\\r?\\n");
int i = 0;
if (lines[0].contains("JRIP")) {
Pattern JRipPattern = Pattern.compile(ruleJRip);
Pattern JRipLabelPattern = Pattern.compile(labelJRip);
for (i = 0; i < lines.length; i++) {
Matcher JRipMatcher = JRipPattern.matcher(lines[i]);
Matcher JRipLabelMatcher = JRipLabelPattern.matcher(lines[i]);
while (JRipMatcher.find()) {
// Attribute name
JRipMatcher.group(1);
/* Relationship, JRipMatcher.group(2) can be =, <, <=, >, >= */
JRipMatcher.group(2);
// Value
JRipMatcher.group(3);
}
if (JRipLabelMatcher.find()) {
// Label
JRipLabelMatcher.group(1);
}
}
}
if (lines[0].contains("PART")) {
Pattern PARTPattern = Pattern.compile(rulePART);
for (i = 1; i < lines.length; i++) {
Matcher PARTMatcher = PARTPattern.matcher(lines[i]);
while (PARTMatcher.find()) {
// Attribute name
PARTMatcher.group(1);
/* Relationship, PARTMatcher.group(2) can be =, <, <=, >, >= */
PARTMatcher.group(2);
// Value
PARTMatcher.group(3);
if (!PARTMatcher.group(5).isEmpty()) {
// Label
PARTMatcher.group(5);
}
}
}
}
if (lines[0].contains("J48")) {
}
if (lines[0].contains("REPTree")) {
}
return ruleList;
}
}
| J48 rules are now being parsed
| src/main/java/eu/musesproject/server/dataminer/ParsingUtils.java | J48 rules are now being parsed | <ide><path>rc/main/java/eu/musesproject/server/dataminer/ParsingUtils.java
<ide> String ruleJRip = "\\((\\w+)([\\s\\>\\=\\<]+)([\\w\\.]+)\\)";
<ide> String labelJRip = "\\=\\>\\s\\w+\\=(\\w+)";
<ide> String rulePART = "(\\w+)([\\s\\>\\=\\<]+)(\\w+)\\s?(AND|\\:)?\\s?(\\w*)";
<del> String ruleJ48 = "";
<add> String ruleJ48 = "\\|*\\s*(\\w+)([\\s\\>\\=\\<]+)(\\w+)\\s?\\:?\\s?(\\w*)";
<ide> String ruleREPTree = "";
<ide> String lines[] = classifierRules.split("\\r?\\n");
<ide> int i = 0;
<ide> if (lines[0].contains("JRIP")) {
<ide> Pattern JRipPattern = Pattern.compile(ruleJRip);
<ide> Pattern JRipLabelPattern = Pattern.compile(labelJRip);
<del> for (i = 0; i < lines.length; i++) {
<add> for (i = 1; i < lines.length; i++) {
<ide> Matcher JRipMatcher = JRipPattern.matcher(lines[i]);
<ide> Matcher JRipLabelMatcher = JRipLabelPattern.matcher(lines[i]);
<ide> while (JRipMatcher.find()) {
<ide>
<ide> }
<ide> if (lines[0].contains("J48")) {
<add> Pattern J48Pattern = Pattern.compile(ruleJ48);
<add> for (i = 1; i < lines.length; i++) {
<add> Matcher J48Matcher = J48Pattern.matcher(lines[i]);
<add> while (J48Matcher.find()) {
<add> logger.info(J48Matcher.group(1));
<add> logger.info(J48Matcher.group(2));
<add> logger.info(J48Matcher.group(3));
<add> // Attribute name
<add> J48Matcher.group(1);
<add> /* Relationship, PARTMatcher.group(2) can be =, <, <=, >, >= */
<add> J48Matcher.group(2);
<add> // Value
<add> J48Matcher.group(3);
<add> if (!J48Matcher.group(4).isEmpty()) {
<add> logger.info(J48Matcher.group(4));
<add> // Label
<add> J48Matcher.group(4);
<add> }
<add> }
<add> }
<ide>
<ide> }
<ide> if (lines[0].contains("REPTree")) { |
|
Java | apache-2.0 | 1cabe82a812be39bb3ebaf0d68f61410ba19e5e9 | 0 | thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck | /*
* Copyright (C) 2002 EBI, GRL
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.ensembl.healthcheck;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.LogFormatter;
import org.ensembl.healthcheck.util.MyStreamHandler;
import org.ensembl.healthcheck.util.Utils;
/**
* Pull healthcheck results from a database and write to an HTML file.
*/
public class DatabaseToHTML {
private boolean debug = false;
private String PROPERTIES_FILE = "database.properties";
private String outputDir = ".";
private long sessionID = -1;
protected static Logger logger = Logger.getLogger("HealthCheckLogger");
/**
* Command-line entry point.
*
* @param args
* Command line args.
*/
public static void main(String[] args) {
new DatabaseToHTML().run(args);
}
// ---------------------------------------------------------------------
/**
* Main run method.
*
* @param args
* Command-line arguments.
*/
private void run(String[] args) {
parseCommandLine(args);
setupLogging();
Utils.readPropertiesFileIntoSystem(PROPERTIES_FILE);
parseProperties();
Connection con = connectToOutputDatabase();
sessionID = getSessionID(sessionID, con);
printOutput(con);
} // run
// ---------------------------------------------------------------------
private void parseCommandLine(String[] args) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-h")) {
printUsage();
System.exit(0);
} else if (args[i].equals("-output")) {
i++;
outputDir = args[i];
logger.finest("Will write output to " + outputDir);
} else if (args[i].equals("-session")) {
i++;
sessionID = Long.parseLong(args[i]);
logger.finest("Will use session ID " + sessionID);
} else if (args[i].equals("-debug")) {
debug = true;
}
}
} // parseCommandLine
// -------------------------------------------------------------------------
private void printUsage() {
System.out.println("\nUsage: DatabaseToHTML {options} \n");
System.out.println("Options:");
System.out.println(" -output Specify output directory. Default is current directory.");
System.out.println(" -h This message.");
System.out.println(" -debug Print debugging info");
System.out.println();
System.out.println("All other configuration information is read from the file database.properties. ");
System.out.println("See the comments in that file for information on which options to set.");
}
// ---------------------------------------------------------------------
private void setupLogging() {
// stop parent logger getting the message
logger.setUseParentHandlers(false);
Handler myHandler = new MyStreamHandler(System.out, new LogFormatter());
logger.addHandler(myHandler);
logger.setLevel(Level.WARNING);
if (debug) {
logger.setLevel(Level.FINEST);
}
} // setupLogging
// ---------------------------------------------------------------------
private void parseProperties() {
}
// ---------------------------------------------------------------------
private Connection connectToOutputDatabase() {
Connection con = DBUtils.openConnection(System.getProperty("output.driver"), System.getProperty("output.databaseURL")
+ System.getProperty("output.database"), System.getProperty("output.user"), System.getProperty("output.password"));
logger.fine("Connecting to " + System.getProperty("output.databaseURL") + System.getProperty("output.database") + " as "
+ System.getProperty("output.user") + " password " + System.getProperty("output.password"));
return con;
}
// ---------------------------------------------------------------------
/**
* Get the most recent session ID from the database, or use the one defined on
* the command line.
*/
private long getSessionID(long s, Connection con) {
long sess = -1;
String sql = "SELECT MAX(session_id) FROM session";
if (s > 0) {
sess = s;
} else {
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
sess = rs.getLong(1);
logger.finest("Maximum session ID from database: " + sess);
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
}
if (sess == 1) {
logger.severe("Can't get session ID from command-line or database.");
}
return sess;
}
// ---------------------------------------------------------------------
/**
* Print formatted output.
*/
private void printOutput(Connection con) {
try {
PrintWriter pwIntro = new PrintWriter(new FileOutputStream(outputDir + File.separator + "index.html"));
printIntroPage(pwIntro, con);
// now loop over each species and print the detailed output
String sql = "SELECT DISTINCT(species) FROM report WHERE session_id=" + sessionID + " ORDER BY species ";
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String species = rs.getString("species");
PrintWriter pw = new PrintWriter(new FileOutputStream(outputDir + File.separator + species + ".html"));
printHeader(pw, species, con);
printNavigation(pw, species, con);
// printExecutiveSummary(pw);
printSummaryByDatabase(pw, species, con);
printSummaryByTest(pw, species, con);
printReportsByDatabase(pw, species, con);
printFooter(pw);
pw.close();
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
pwIntro.close();
} catch (Exception e) {
System.err.println("Error writing output");
e.printStackTrace();
}
}
// ---------------------------------------------------------------------
private void printIntroPage(PrintWriter pw, Connection con) {
// header
print(pw, "<html>");
print(pw, "<head>");
print(pw, "<!--#set var=\"decor\" value=\"none\"-->");
print(pw, "<style type='text/css' media='all'>");
print(pw, "@import url(http://www.ensembl.org/css/ensembl.css);");
print(pw, "@import url(http://www.ensembl.org/css/content.css);");
print(pw, "#page ul li { list-style-type:none; list-style-image: none; margin-left: -2em }");
print(pw, "</style>");
print(pw, "<title>Healthcheck Results</title>");
print(pw, "</head>");
print(pw, "<body>");
print(pw, "<div id='page'><div id='i1'><div id='i2'><div class='sptop'> </div>");
print(pw, "<div id='release'>Healthcheck results</div>");
print(pw, "<hr>");
print(pw, "");
print(pw, "<h2>Results by species</h2>");
print(pw, "<ul>");
// now loop over each species
String sql = "SELECT DISTINCT(species) FROM report WHERE session_id = " + sessionID + " ORDER BY species";
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String species = rs.getString("species");
print(pw, "<li><p><a href='" + species + ".html'>" + Utils.ucFirst(species) + "</a></p></li>");
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
// footer
print(pw, "</ul>");
print(pw, "");
print(pw, "<hr>");
print(pw, "");
print(pw, "<h3>Previous releases</h3>");
print(pw, "");
print(pw, "<ul>");
print(pw, "<li><a href='previous/40/index.html'>40</a> (August 2006)</li>");
print(pw, "<li><a href='previous/39/web_healthcheck_summary.html'>39</a> (June 2006)</li>");
print(pw, "<li><a href='previous/38/web_healthcheck_summary.html'>38</a> (April 2006)</li>");
print(pw, "</ul>");
print(pw, "<hr>");
sql = "SELECT start_time, end_time, host, groups, database_regexp FROM session WHERE session_id = " + sessionID;
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
print(pw, "<p>Test run was started at " + rs.getString("start_time") + " and finished at " + rs.getString("end_time")
+ "<br>");
print(pw, "<h4>Configuration used:</h4>");
print(pw, "<pre>");
print(pw, "Tests/groups run: " + rs.getString("groups") + "<br>");
print(pw, "Database host: " + rs.getString("host") + "<br>");
print(pw, "Database names: " + rs.getString("database_regexp") + "<br>");
print(pw, "</pre>");
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
print(pw, "</body>");
print(pw, "</html>");
print(pw, "<hr>");
}
// ---------------------------------------------------------------------
private void printHeader(PrintWriter pw, String species, Connection con) {
print(pw, "<html>");
print(pw, "<head>");
print(pw, "<!--#set var=\"decor\" value=\"none\"-->");
print(pw, "<style type=\"text/css\" media=\"all\">");
print(pw, "@import url(http://www.ensembl.org/css/ensembl.css);");
print(pw, "@import url(http://www.ensembl.org/css/content.css);");
print(pw, "#page ul li { list-style-type:none; list-style-image: none; margin-left: -2em }");
print(pw, "td { font-size: 9pt}");
print(pw, "</style>");
print(pw, "<title>Healthcheck results for " + Utils.ucFirst(species) + "</title>");
print(pw, "</head>");
print(pw, "<body>");
print(pw, "<div id='page'><div id='i1'><div id='i2'><div class='sptop'> </div>");
print(pw, "<div id='release'>Healthcheck results for " + Utils.ucFirst(species) + "</div>");
print(pw, "<hr>");
}
// ---------------------------------------------------------------------
private void printFooter(PrintWriter pw) {
print(pw, "</div>");
print(pw, "</body>");
print(pw, "</html>");
}
// ---------------------------------------------------------------------
private void printNavigation(PrintWriter pw, String species, Connection con) {
print(pw, "<div id='related'><div id='related-box'>");
// results by database
print(pw, "<h2>Results by database</h2>");
print(pw, "<ul>");
String sql = "SELECT DISTINCT(database_name) FROM report WHERE species='" + species + "' AND session_id=" + sessionID;
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String database = rs.getString(1);
String link = "<a href=\"#" + database + "\">";
print(pw, "<li>" + link + Utils.truncateDatabaseName(database) + "</a></li>");
}
print(pw, "</ul>");
// results by test
print(pw, "<h2>Failures by test</h2>");
print(pw, "<ul>");
sql = "SELECT DISTINCT(testcase) FROM report WHERE species='" + species + "' AND result IN ('PROBLEM','WARNING','INFO') AND session_id=" + sessionID;
rs = stmt.executeQuery(sql);
while (rs.next()) {
String test = rs.getString(1);
String name = test.substring(test.lastIndexOf('.') + 1);
String link = "<a href=\"#" + name + "\">";
print(pw, "<li>" + link + Utils.truncateTestName(name) + "</a></li>");
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
print(pw, "</ul>");
print(pw, "</div></div>");
}
// ---------------------------------------------------------------------
private void printSummaryByDatabase(PrintWriter pw, String species, Connection con) {
print(pw, "<h2>Summary of results by database</h2>");
print(pw, "<p><table class='ss'>");
print(pw, "<tr><th>Database</th><th>Passed</th><th>Failed</th></tr>");
String sql = "SELECT DISTINCT(database_name) FROM report WHERE species='" + species + "' AND session_id=" + sessionID;
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String database = rs.getString(1);
String link = "<a href=\"#" + database + "\">";
int[] passesAndFails = countPassesAndFailsDatabase(database, con);
String s = (passesAndFails[1] == 0) ? passFont() : failFont();
String[] t = { link + s + database + "</font></a>", passFont() + passesAndFails[0] + "</font>",
failFont() + passesAndFails[1] + "</font>" };
printTableLine(pw, t);
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
print(pw, "</table></p>");
print(pw, "<hr>");
}
// ---------------------------------------------------------------------
private void print(PrintWriter pw, String s) {
pw.write(s + "\n");
pw.flush();
}
// ---------------------------------------------------------------------
private void printTableLine(PrintWriter pw, String[] s) {
pw.write("<tr>");
for (int i = 0; i < s.length; i++) {
pw.write("<td>" + s[i] + "</td>");
}
pw.write("</tr>\n");
}
// ---------------------------------------------------------------------
private String passFont() {
return "<font color='green' size=-1>";
}
// ---------------------------------------------------------------------
private String failFont() {
return "<font color='red' size=-1>";
}
// ---------------------------------------------------------------------
private int[] countPassesAndFailsDatabase(String database, Connection con) {
int[] result = new int[2];
int total = -1, failed = -1;
// get count of total tests run
String sql = "SELECT COUNT(DISTINCT(testcase)) FROM report WHERE database_name='" + database + "' AND session_id=" + sessionID;
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
total = rs.getInt(1);
}
sql = "SELECT COUNT(DISTINCT(testcase)) FROM report WHERE database_name='" + database
+ "' AND result = 'PROBLEM' AND session_id=" + sessionID;
rs = stmt.executeQuery(sql);
if (rs.next()) {
failed = rs.getInt(1);
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
result[1] = failed;
result[0] = total - failed;
return result;
}
// ------
private void printSummaryByTest(PrintWriter pw, String species, Connection con) {
print(pw, "<h2>Summary of failures by test</h2>");
print(pw, "<p><table class='ss'>");
print(pw, "<tr><th>Test</th><th>Result</th></tr>");
// group failed tests before passed ones via ORDER BY
String sql = "SELECT DISTINCT(testcase), result FROM report WHERE species='" + species + "' AND session_id=" + sessionID
+ " AND result IN ('PROBLEM','WARNING','INFO') ORDER BY result";
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String testcase = rs.getString(1);
String result = rs.getString(2);
String link = "<a href=\"#" + testcase + "\">";
String s = (result.equals("CORRECT")) ? passFont() : failFont();
String r = (result.equals("CORRECT")) ? "Passed" : "Failed";
String[] t = { link + s + testcase + "</a></font>", s + r + "</font>" };
printTableLine(pw, t);
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
print(pw, "</table></p>");
print(pw, "<hr>");
}
// ---------------------------------------------------------------------
private void printReportsByDatabase(PrintWriter pw, String species, Connection con) {
print(pw, "<h2>Detailed failure reports by database</h2>");
String sql = "SELECT r.report_id, r.database_name, r.testcase, r.result, r.text, a.person, a.action, a.reason, a.comment FROM report r LEFT JOIN annotation a ON r.report_id=a.report_id WHERE r.species='" + species + "' AND r.session_id=" + sessionID + " AND r.result IN ('PROBLEM','WARNING','INFO') ORDER BY r.database_name, r.testcase";
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
String lastDatabase = "";
String lastTest = "";
while (rs.next()) {
String database = rs.getString("database_name");
String testcase = rs.getString("testcase");
String result = rs.getString("result");
String text = rs.getString("text");
String person = stringOrBlank(rs.getString("person"));
String action = stringOrBlank(rs.getString("action"));
String reason = stringOrBlank(rs.getString("reason"));
String comment = stringOrBlank(rs.getString("comment"));
if (!database.equals(lastDatabase)) {
if (lastDatabase != "") {
print(pw, "</table>");
}
String link = "<a name=\"" + database + "\">";
print(pw, "<h3 class='boxed'>" + link + database + "</a></h3>");
print(pw, "<table>");
lastDatabase = database;
}
String f1 = getFontForResult(result, action);
String f2 = "</font>";
if (!testcase.equals(lastTest)) {
String linkTarget = "<a name=\"" + database + ":" + testcase + "\"></a> ";
print(pw, "<tr><td colspan='6'>" + linkTarget + f1 + "<strong>" + testcase + "</strong>" + f2 + "</td></tr>");
}
lastTest = testcase;
String[] s = {" ", f1 + text + f2, f1 + person + f2, f1 + action + f2, f1 + comment + f2};
printTableLine(pw, s);
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
}
// ---------------------------------------------------------------------
private String getFontForResult(String result, String action) {
String s1 = "<font color='black'>";
if (result.equals("PROBLEM")) {
s1 = "<font color='red'>";
}
if (result.equals("WARNING")) {
s1 = "<font color='black'>";
}
if (result.equals("INFO")) {
s1 = "<font color='black'>";
}
if (result.equals("CORRECT")) {
s1 = "<font color='green'>";
}
if (result.equals("")) {
s1 = "<font color='red'>";
}
if (result.equals("PROBLEM")) {
s1 = "<font color='red'>";
}
// override if there has been an annotation
if (action != null) {
if(action.equals("ignore") || action.equals("normal")) {
s1 = "<font color='grey'>";
}
}
return s1;
}
//---------------------------------------------------------------------
private String stringOrBlank(String s) {
return (s != null) ? s : "";
}
// ---------------------------------------------------------------------
} // DatabaseToHTML
| src/org/ensembl/healthcheck/DatabaseToHTML.java | /*
* Copyright (C) 2002 EBI, GRL
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.ensembl.healthcheck;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.LogFormatter;
import org.ensembl.healthcheck.util.MyStreamHandler;
import org.ensembl.healthcheck.util.Utils;
/**
* Pull healthcheck results from a database and write to an HTML file.
*/
public class DatabaseToHTML {
private boolean debug = false;
private String PROPERTIES_FILE = "database.properties";
private String outputDir = ".";
private long sessionID = -1;
protected static Logger logger = Logger.getLogger("HealthCheckLogger");
/**
* Command-line entry point.
*
* @param args
* Command line args.
*/
public static void main(String[] args) {
new DatabaseToHTML().run(args);
}
// ---------------------------------------------------------------------
/**
* Main run method.
*
* @param args
* Command-line arguments.
*/
private void run(String[] args) {
parseCommandLine(args);
setupLogging();
Utils.readPropertiesFileIntoSystem(PROPERTIES_FILE);
parseProperties();
Connection con = connectToOutputDatabase();
sessionID = getSessionID(sessionID, con);
printOutput(con);
} // run
// ---------------------------------------------------------------------
private void parseCommandLine(String[] args) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-h")) {
printUsage();
System.exit(0);
} else if (args[i].equals("-output")) {
i++;
outputDir = args[i];
logger.finest("Will write output to " + outputDir);
} else if (args[i].equals("-session")) {
i++;
sessionID = Long.parseLong(args[i]);
logger.finest("Will use session ID " + sessionID);
} else if (args[i].equals("-debug")) {
debug = true;
}
}
} // parseCommandLine
// -------------------------------------------------------------------------
private void printUsage() {
System.out.println("\nUsage: DatabaseToHTML {options} \n");
System.out.println("Options:");
System.out.println(" -output Specify output directory. Default is current directory.");
System.out.println(" -h This message.");
System.out.println(" -debug Print debugging info");
System.out.println();
System.out.println("All other configuration information is read from the file database.properties. ");
System.out.println("See the comments in that file for information on which options to set.");
}
// ---------------------------------------------------------------------
private void setupLogging() {
// stop parent logger getting the message
logger.setUseParentHandlers(false);
Handler myHandler = new MyStreamHandler(System.out, new LogFormatter());
logger.addHandler(myHandler);
logger.setLevel(Level.WARNING);
if (debug) {
logger.setLevel(Level.FINEST);
}
} // setupLogging
// ---------------------------------------------------------------------
private void parseProperties() {
}
// ---------------------------------------------------------------------
private Connection connectToOutputDatabase() {
Connection con = DBUtils.openConnection(System.getProperty("output.driver"), System.getProperty("output.databaseURL")
+ System.getProperty("output.database"), System.getProperty("output.user"), System.getProperty("output.password"));
logger.fine("Connecting to " + System.getProperty("output.databaseURL") + System.getProperty("output.database") + " as "
+ System.getProperty("output.user") + " password " + System.getProperty("output.password"));
return con;
}
// ---------------------------------------------------------------------
/**
* Get the most recent session ID from the database, or use the one defined on
* the command line.
*/
private long getSessionID(long s, Connection con) {
long sess = -1;
String sql = "SELECT MAX(session_id) FROM session";
if (s > 0) {
sess = s;
} else {
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
sess = rs.getLong(1);
logger.finest("Maximum session ID from database: " + sess);
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
}
if (sess == 1) {
logger.severe("Can't get session ID from command-line or database.");
}
return sess;
}
// ---------------------------------------------------------------------
/**
* Print formatted output.
*/
private void printOutput(Connection con) {
try {
PrintWriter pwIntro = new PrintWriter(new FileOutputStream(outputDir + File.separator + "index.html"));
printIntroPage(pwIntro, con);
// now loop over each species and print the detailed output
String sql = "SELECT DISTINCT(species) FROM report WHERE session_id=" + sessionID + " ORDER BY species ";
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String species = rs.getString("species");
PrintWriter pw = new PrintWriter(new FileOutputStream(outputDir + File.separator + species + ".html"));
printHeader(pw, species, con);
printNavigation(pw, species, con);
// printExecutiveSummary(pw);
printSummaryByDatabase(pw, species, con);
printSummaryByTest(pw, species, con);
printReportsByDatabase(pw, species, con);
printFooter(pw);
pw.close();
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
pwIntro.close();
} catch (Exception e) {
System.err.println("Error writing output");
e.printStackTrace();
}
}
// ---------------------------------------------------------------------
private void printIntroPage(PrintWriter pw, Connection con) {
// header
print(pw, "<html>");
print(pw, "<head>");
print(pw, "<!--#set var=\"decor\" value=\"none\"-->");
print(pw, "<style type='text/css' media='all'>");
print(pw, "@import url(http://www.ensembl.org/css/ensembl.css);");
print(pw, "@import url(http://www.ensembl.org/css/content.css);");
print(pw, "#page ul li { list-style-type:none; list-style-image: none; margin-left: -2em }");
print(pw, "</style>");
print(pw, "<title>Healthcheck Results</title>");
print(pw, "</head>");
print(pw, "<body>");
print(pw, "<div id='page'><div id='i1'><div id='i2'><div class='sptop'> </div>");
print(pw, "<div id='release'>Healthcheck results</div>");
print(pw, "<hr>");
print(pw, "");
print(pw, "<h2>Results by species</h2>");
print(pw, "<ul>");
// now loop over each species
String sql = "SELECT DISTINCT(species) FROM report WHERE session_id = " + sessionID + " ORDER BY species";
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String species = rs.getString("species");
print(pw, "<li><p><a href='" + species + ".html'>" + Utils.ucFirst(species) + "</a></p></li>");
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
// footer
print(pw, "</ul>");
print(pw, "");
print(pw, "<hr>");
print(pw, "");
print(pw, "<h3>Previous releases</h3>");
print(pw, "");
print(pw, "<ul>");
print(pw, "<li><a href='previous/39/web_healthcheck_summary.html'>39</a> (June 2006)</li>");
print(pw, "<li><a href='previous/38/web_healthcheck_summary.html'>38</a> (April 2006)</li>");
print(pw, "</ul>");
print(pw, "<hr>");
sql = "SELECT start_time, end_time, host, groups, database_regexp FROM session WHERE session_id = " + sessionID;
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
print(pw, "<p>Test run was started at " + rs.getString("start_time") + " and finished at " + rs.getString("end_time")
+ "<br>");
print(pw, "<h4>Configuration used:</h4>");
print(pw, "<pre>");
print(pw, "Tests/groups run: " + rs.getString("groups") + "<br>");
print(pw, "Database host: " + rs.getString("host") + "<br>");
print(pw, "Database names: " + rs.getString("database_regexp") + "<br>");
print(pw, "</pre>");
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
print(pw, "</body>");
print(pw, "</html>");
print(pw, "<hr>");
}
// ---------------------------------------------------------------------
private void printHeader(PrintWriter pw, String species, Connection con) {
print(pw, "<html>");
print(pw, "<head>");
print(pw, "<!--#set var=\"decor\" value=\"none\"-->");
print(pw, "<style type=\"text/css\" media=\"all\">");
print(pw, "@import url(http://www.ensembl.org/css/ensembl.css);");
print(pw, "@import url(http://www.ensembl.org/css/content.css);");
print(pw, "#page ul li { list-style-type:none; list-style-image: none; margin-left: -2em }");
print(pw, "td { font-size: 9pt}");
print(pw, "</style>");
print(pw, "<title>Healthcheck results for " + Utils.ucFirst(species) + "</title>");
print(pw, "</head>");
print(pw, "<body>");
print(pw, "<div id='page'><div id='i1'><div id='i2'><div class='sptop'> </div>");
print(pw, "<div id='release'>Healthcheck results for " + Utils.ucFirst(species) + "</div>");
print(pw, "<hr>");
}
// ---------------------------------------------------------------------
private void printFooter(PrintWriter pw) {
print(pw, "</div>");
print(pw, "</body>");
print(pw, "</html>");
}
// ---------------------------------------------------------------------
private void printNavigation(PrintWriter pw, String species, Connection con) {
print(pw, "<div id='related'><div id='related-box'>");
// results by database
print(pw, "<h2>Results by database</h2>");
print(pw, "<ul>");
String sql = "SELECT DISTINCT(database_name) FROM report WHERE species='" + species + "' AND session_id=" + sessionID;
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String database = rs.getString(1);
String link = "<a href=\"#" + database + "\">";
print(pw, "<li>" + link + Utils.truncateDatabaseName(database) + "</a></li>");
}
print(pw, "</ul>");
// results by test
print(pw, "<h2>Failures by test</h2>");
print(pw, "<ul>");
sql = "SELECT DISTINCT(testcase) FROM report WHERE species='" + species + "' AND result IN ('PROBLEM','WARNING','INFO') AND session_id=" + sessionID;
rs = stmt.executeQuery(sql);
while (rs.next()) {
String test = rs.getString(1);
String name = test.substring(test.lastIndexOf('.') + 1);
String link = "<a href=\"#" + name + "\">";
print(pw, "<li>" + link + Utils.truncateTestName(name) + "</a></li>");
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
print(pw, "</ul>");
print(pw, "</div></div>");
}
// ---------------------------------------------------------------------
private void printSummaryByDatabase(PrintWriter pw, String species, Connection con) {
print(pw, "<h2>Summary of results by database</h2>");
print(pw, "<p><table class='ss'>");
print(pw, "<tr><th>Database</th><th>Passed</th><th>Failed</th></tr>");
String sql = "SELECT DISTINCT(database_name) FROM report WHERE species='" + species + "' AND session_id=" + sessionID;
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String database = rs.getString(1);
String link = "<a href=\"#" + database + "\">";
int[] passesAndFails = countPassesAndFailsDatabase(database, con);
String s = (passesAndFails[1] == 0) ? passFont() : failFont();
String[] t = { link + s + database + "</font></a>", passFont() + passesAndFails[0] + "</font>",
failFont() + passesAndFails[1] + "</font>" };
printTableLine(pw, t);
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
print(pw, "</table></p>");
print(pw, "<hr>");
}
// ---------------------------------------------------------------------
private void print(PrintWriter pw, String s) {
pw.write(s + "\n");
pw.flush();
}
// ---------------------------------------------------------------------
private void printTableLine(PrintWriter pw, String[] s) {
pw.write("<tr>");
for (int i = 0; i < s.length; i++) {
pw.write("<td>" + s[i] + "</td>");
}
pw.write("</tr>\n");
}
// ---------------------------------------------------------------------
private String passFont() {
return "<font color='green' size=-1>";
}
// ---------------------------------------------------------------------
private String failFont() {
return "<font color='red' size=-1>";
}
// ---------------------------------------------------------------------
private int[] countPassesAndFailsDatabase(String database, Connection con) {
int[] result = new int[2];
int total = -1, failed = -1;
// get count of total tests run
String sql = "SELECT COUNT(DISTINCT(testcase)) FROM report WHERE database_name='" + database + "' AND session_id=" + sessionID;
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
total = rs.getInt(1);
}
sql = "SELECT COUNT(DISTINCT(testcase)) FROM report WHERE database_name='" + database
+ "' AND result = 'PROBLEM' AND session_id=" + sessionID;
rs = stmt.executeQuery(sql);
if (rs.next()) {
failed = rs.getInt(1);
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
result[1] = failed;
result[0] = total - failed;
return result;
}
// ------
private void printSummaryByTest(PrintWriter pw, String species, Connection con) {
print(pw, "<h2>Summary of failures by test</h2>");
print(pw, "<p><table class='ss'>");
print(pw, "<tr><th>Test</th><th>Result</th></tr>");
// group failed tests before passed ones via ORDER BY
String sql = "SELECT DISTINCT(testcase), result FROM report WHERE species='" + species + "' AND session_id=" + sessionID
+ " AND result IN ('PROBLEM','WARNING','INFO') ORDER BY result";
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String testcase = rs.getString(1);
String result = rs.getString(2);
String link = "<a href=\"#" + testcase + "\">";
String s = (result.equals("CORRECT")) ? passFont() : failFont();
String r = (result.equals("CORRECT")) ? "Passed" : "Failed";
String[] t = { link + s + testcase + "</a></font>", s + r + "</font>" };
printTableLine(pw, t);
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
print(pw, "</table></p>");
print(pw, "<hr>");
}
// ---------------------------------------------------------------------
private void printReportsByDatabase(PrintWriter pw, String species, Connection con) {
print(pw, "<h2>Detailed failure reports by database</h2>");
String sql = "SELECT r.report_id, r.database_name, r.testcase, r.result, r.text, a.person, a.action, a.reason, a.comment FROM report r LEFT JOIN annotation a ON r.report_id=a.report_id WHERE r.species='" + species + "' AND r.session_id=" + sessionID + " AND r.result IN ('PROBLEM','WARNING','INFO') ORDER BY r.database_name, r.testcase";
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
String lastDatabase = "";
String lastTest = "";
while (rs.next()) {
String database = rs.getString("database_name");
String testcase = rs.getString("testcase");
String result = rs.getString("result");
String text = rs.getString("text");
String person = stringOrBlank(rs.getString("person"));
String action = stringOrBlank(rs.getString("action"));
String reason = stringOrBlank(rs.getString("reason"));
String comment = stringOrBlank(rs.getString("comment"));
if (!database.equals(lastDatabase)) {
if (lastDatabase != "") {
print(pw, "</table>");
}
String link = "<a name=\"" + database + "\">";
print(pw, "<h3 class='boxed'>" + link + database + "</a></h3>");
print(pw, "<table>");
lastDatabase = database;
}
String f1 = getFontForResult(result, action);
String f2 = "</font>";
if (!testcase.equals(lastTest)) {
String linkTarget = "<a name=\"" + database + ":" + testcase + "\"></a> ";
print(pw, "<tr><td colspan='6'>" + linkTarget + f1 + "<strong>" + testcase + "</strong>" + f2 + "</td></tr>");
}
lastTest = testcase;
String[] s = {" ", f1 + text + f2, f1 + person + f2, f1 + action + f2, f1 + comment + f2};
printTableLine(pw, s);
}
} catch (SQLException e) {
System.err.println("Error executing:\n" + sql);
e.printStackTrace();
}
}
// ---------------------------------------------------------------------
private String getFontForResult(String result, String action) {
String s1 = "<font color='black'>";
if (result.equals("PROBLEM")) {
s1 = "<font color='red'>";
}
if (result.equals("WARNING")) {
s1 = "<font color='black'>";
}
if (result.equals("INFO")) {
s1 = "<font color='black'>";
}
if (result.equals("CORRECT")) {
s1 = "<font color='green'>";
}
if (result.equals("")) {
s1 = "<font color='red'>";
}
if (result.equals("PROBLEM")) {
s1 = "<font color='red'>";
}
// override if there has been an annotation
if (action != null) {
if(action.equals("ignore") || action.equals("normal")) {
s1 = "<font color='grey'>";
}
}
return s1;
}
//---------------------------------------------------------------------
private String stringOrBlank(String s) {
return (s != null) ? s : "";
}
// ---------------------------------------------------------------------
} // DatabaseToHTML
| Add release 40 to previous list.
| src/org/ensembl/healthcheck/DatabaseToHTML.java | Add release 40 to previous list. | <ide><path>rc/org/ensembl/healthcheck/DatabaseToHTML.java
<ide> print(pw, "<h3>Previous releases</h3>");
<ide> print(pw, "");
<ide> print(pw, "<ul>");
<add> print(pw, "<li><a href='previous/40/index.html'>40</a> (August 2006)</li>");
<ide> print(pw, "<li><a href='previous/39/web_healthcheck_summary.html'>39</a> (June 2006)</li>");
<ide> print(pw, "<li><a href='previous/38/web_healthcheck_summary.html'>38</a> (April 2006)</li>");
<ide> print(pw, "</ul>"); |
|
Java | apache-2.0 | 9d55dd696ec74d71128a5c38deb7af64a2d9a62e | 0 | korpling/ANNIS,zangsir/ANNIS,zangsir/ANNIS,thomaskrause/ANNIS,thomaskrause/ANNIS,thomaskrause/ANNIS,zangsir/ANNIS,thomaskrause/ANNIS,korpling/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,thomaskrause/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,zangsir/ANNIS,zangsir/ANNIS,korpling/ANNIS,amir-zeldes/ANNIS,korpling/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS,korpling/ANNIS | /*
* Copyright 2010 Collaborative Research Centre SFB 632.
*
* 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.
* under the License.
*/
package annis.frontend.servlets.visualizers.graph;
import annis.frontend.servlets.visualizers.WriterVisualizer;
import annis.model.AnnisNode;
import annis.model.Edge;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Thomas Krause
*/
public class DotGraphVisualizer extends WriterVisualizer
{
private String outputFormat = "png";
private int scale = 50;
private StringBuilder nodeDefinitions;
private StringBuilder edgeDefinitions;
@Override
public void writeOutput(Writer writer)
{
nodeDefinitions = new StringBuilder();
edgeDefinitions = new StringBuilder();
for (AnnisNode n : getResult().getGraph().getNodes())
{
writeNode(n);
}
for (Edge e : getResult().getGraph().getEdges())
{
writeEdge(e);
}
try
{
String cmd = getDotPath() + " -s" + scale + ".0 -T" + outputFormat;
Runtime runTime = Runtime.getRuntime();
Process p = runTime.exec(cmd);
StringWriter debugStdin = new StringWriter();
OutputStreamWriter stdin = new OutputStreamWriter(p.getOutputStream(), "UTF-8");
writeDOT(stdin);
writeDOT(debugStdin);
stdin.flush();
p.getOutputStream().close();
int chr;
InputStream stdout = p.getInputStream();
StringBuilder outMessage = new StringBuilder();
while ((chr = stdout.read()) != -1)
{
writer.write(chr);
outMessage.append((char) chr);
}
StringBuilder errorMessage = new StringBuilder();
InputStream stderr = p.getErrorStream();
while ((chr = stderr.read()) != -1)
{
errorMessage.append((char) chr);
}
p.destroy();
writer.flush();
}
catch (IOException ex)
{
Logger.getLogger(DotGraphVisualizer.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void writeDOT(Writer writer) throws IOException
{
writer.append("digraph G {\n");
writer.append(nodeDefinitions);
writer.append(edgeDefinitions);
writer.append("}");
}
private void writeNode(AnnisNode node)
{
nodeDefinitions.append("\"");
nodeDefinitions.append(node.getName());
nodeDefinitions.append("\";\n");
}
private void writeEdge(Edge edge)
{
// TODO
}
@Override
public String getContentType()
{
return "image/png";
}
@Override
public String getCharacterEncoding()
{
return "ISO-8859-1";
}
}
| Annis-Web/src/main/java/annis/frontend/servlets/visualizers/graph/DotGraphVisualizer.java | /*
* Copyright 2010 Collaborative Research Centre SFB 632.
*
* 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.
* under the License.
*/
package annis.frontend.servlets.visualizers.graph;
import annis.frontend.servlets.visualizers.WriterVisualizer;
import annis.model.AnnisNode;
import annis.model.Edge;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Thomas Krause
*/
public class DotGraphVisualizer extends WriterVisualizer
{
private String outputFormat = "dot";
private int scale = 50;
private StringBuilder nodeDefinitions;
private StringBuilder edgeDefinitions;
@Override
public void writeOutput(Writer writer)
{
nodeDefinitions = new StringBuilder();
edgeDefinitions = new StringBuilder();
for (AnnisNode n : getResult().getGraph().getNodes())
{
writeNode(n);
}
for (Edge e : getResult().getGraph().getEdges())
{
writeEdge(e);
}
try
{
String cmd = getDotPath() + " -s" + scale + ".0 -T" + outputFormat;
Runtime runTime = Runtime.getRuntime();
Process p = runTime.exec(cmd);
StringWriter debugStdin = new StringWriter();
OutputStreamWriter stdin = new OutputStreamWriter(p.getOutputStream(), "UTF-8");
writeDOT(stdin);
writeDOT(debugStdin);
stdin.flush();
p.getOutputStream().close();
int chr;
InputStream stdout = p.getInputStream();
StringBuilder outMessage = new StringBuilder();
while ((chr = stdout.read()) != -1)
{
writer.write(chr);
outMessage.append((char) chr);
}
StringBuilder errorMessage = new StringBuilder();
InputStream stderr = p.getErrorStream();
while ((chr = stderr.read()) != -1)
{
errorMessage.append((char) chr);
}
p.destroy();
writer.flush();
}
catch (IOException ex)
{
Logger.getLogger(DotGraphVisualizer.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void writeDOT(Writer writer) throws IOException
{
writer.append("digraph G {\n");
writer.append(nodeDefinitions);
writer.append(edgeDefinitions);
writer.append("}");
}
private void writeNode(AnnisNode node)
{
nodeDefinitions.append("\"");
nodeDefinitions.append(node.getName());
nodeDefinitions.append("\";\n");
}
private void writeEdge(Edge edge)
{
// TODO
}
@Override
public String getContentType()
{
return "text/plain";
}
}
| - output PNG | Annis-Web/src/main/java/annis/frontend/servlets/visualizers/graph/DotGraphVisualizer.java | - output PNG | <ide><path>nnis-Web/src/main/java/annis/frontend/servlets/visualizers/graph/DotGraphVisualizer.java
<ide> public class DotGraphVisualizer extends WriterVisualizer
<ide> {
<ide>
<del> private String outputFormat = "dot";
<add> private String outputFormat = "png";
<ide> private int scale = 50;
<ide> private StringBuilder nodeDefinitions;
<ide> private StringBuilder edgeDefinitions;
<ide> @Override
<ide> public String getContentType()
<ide> {
<del> return "text/plain";
<add> return "image/png";
<ide> }
<add>
<add> @Override
<add> public String getCharacterEncoding()
<add> {
<add> return "ISO-8859-1";
<add> }
<add>
<add>
<ide> } |
|
Java | lgpl-2.1 | d157e4f63f9b5e322c40006225439b69eb623e44 | 0 | bcosenza/patus,bcosenza/patus,bcosenza/patus,bcosenza/patus,bcosenza/patus | package stenciltune;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
/**
* Automatic generation of stencil patterns and stencil code.
* Each pattern is a collection of points (2d or 3d) following common stencil pattern,
* such as Laplacian, hypercube, hyperplane and lines.
* Additional information about feature encoding is in the file feature_encoding.txt.
* @author Biagio
*/
public class StencilGenerator {
public static String outputFolderString = "temp/ml_stencil_code";
public static File outputFolder;
/* static initialization block */
static {
// creating an output dir
outputFolder = new File(outputFolderString);
if(outputFolder.mkdirs()){
System.err.println("Error while creating the autogen output folder: " + outputFolder);
}
}
private PrintStream out;
public StencilGenerator(){
this.out = System.out;
}
public StencilGenerator(PrintStream ps){
this.out = ps;
}
public StencilGenerator(String stencilName) throws IOException {
File stencilFile = new File(outputFolder, stencilName);
stencilFile.createNewFile();
this.out = new PrintStream(stencilFile);
}
public void close(){
this.out.close();
}
/**
*
*
**W** LaPlacian
*
*
*/
public StencilPattern getLaPlacian2D(int size){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
sp.add(new Point2D(0, 0));
for(int i= -size; i<=size; i++)
if(i!=0)
sp.add(new Point2D( i, 0));
for(int i= -size; i<=size; i++)
if(i!=0)
sp.add(new Point2D( 0, i));
sp.sort();
return sp;
}
public StencilPattern getLaPlacian3D(int size){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
sp.add(new Point3D(0, 0, 0));
for(int i= -size; i<=size; i++)
if(i!=0)
sp.add(new Point3D( i, 0, 0));
for(int i= -size; i<=size; i++)
if(i!=0)
sp.add(new Point3D( 0, i, 0));
for(int i= -size; i<=size; i++)
if(i!=0)
sp.add(new Point3D( 0, 0, i));
sp.sort();
return sp;
}
/**
*
*
W Line (spanning only on one dimension)
*
*
*/
public StencilPattern getLine2D(int size, int dim){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
sp.add(new Point2D(0, 0));
if(dim == 0)
for(int i=1; i<=size; i++){
sp.add(new Point2D( i, 0));
sp.add(new Point2D(-i, 0));
}
else
if (dim == 1)
for(int i=1; i<=size; i++){
sp.add(new Point2D( 0, i));
sp.add(new Point2D( 0,-i));
}
else throw new RuntimeException("Dimension not supported (only 0 and 1) instead of "+dim);
sp.sort();
return sp;
}
public StencilPattern getLine3D(int size, int dim){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
sp.add(new Point3D(0, 0,0));
switch(dim){
case 0:
for(int i=1; i<=size; i++){
sp.add(new Point3D( i, 0, 0));
sp.add(new Point3D(-i, 0, 0));
}
break;
case 1:
for(int i=1; i<=size; i++){
sp.add(new Point3D( 0, i, 0));
sp.add(new Point3D( 0,-i, 0));
}
break;
case 2:
for(int i=1; i<=size; i++){
sp.add(new Point3D( 0, 0, i));
sp.add(new Point3D( 0, 0,-i));
}
break;
default:
throw new RuntimeException("Dimension not supported (only 0, 1 and 2) instead of "+dim);
}
sp.sort();
return sp;
}
/**
*
*
W Hyper-plane (only 3d, spans one 2 of 3 dimensions)
*
*
*/
/* dim indicates the free dimension */
public StencilPattern getHyperplane3D(int size, int dim){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
// sp.add(new Point3D(0, 0, 0));
switch(dim){
case 0:
for(int i=-size; i<=size; i++)
for(int j=-size; j<=size; j++)
{
sp.add(new Point3D( i, j, 0));
}
break;
case 1:
for(int i=-size; i<=size; i++)
for(int j=-size; j<=size; j++)
{
sp.add(new Point3D( i, 0, j));
}
break;
case 2:
for(int i=-size; i<=size; i++)
for(int j=-size; j<=size; j++)
{
sp.add(new Point3D( 0, i, j));
}
break;
default:
throw new RuntimeException("Dimension not supported (only 0, 1 and 2) instead of "+dim);
}
sp.sort();
return sp;
}
/**
*****
*****
**W** Hyper-cube
*****
*****
*/
public StencilPattern getHypercube2D(int size){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
for(int i= -size; i<=size; i++)
for(int j= -size; j<=size; j++)
{
sp.add(new Point2D( i, j));
}
sp.sort();
return sp;
}
public StencilPattern getHypercube3D(int size){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
for(int i= -size; i<=size; i++)
for(int j= -size; j<=size; j++)
for(int k= -size; k<=size; k++)
{
sp.add(new Point3D( i, j, k));
}
sp.sort();
return sp;
}
/**
* Generate Patus' DSL code from an input 2D stencil pattern.
* The code is printed into a PrintStream.
*
* IMPORTANT NOTE: current implementation only supports <bufferNum> = 1
*/
public void generate2DStencilCode(InputParams ip){
String typeName = (ip.getTypeSize()==0) ? "float" : "double";
StencilPattern sp = ip.getPattern();
out.println("/* auto-gen 2d stencil for pattern: ");
out.println(" "+ ip.getPattern().toString() );
// Note: input size is not encoded here (is not in InputParams), as it changes at execution time
out.println(" "+ ip.toEncodedString() );
out.println("*/");
out.println("stencil autogen2d (");
// --- case bufNum is 1
if(ip.getBufferNum() == 1){
// arguments
out.println(" "+ typeName +" grid U) {");
// body
out.println(" domainsize = ("+sp.getMaxRadius()+" .. width-"+sp.getMaxRadius()+", "+sp.getMaxRadius()+" .. height-"+sp.getMaxRadius()+");");
out.println();
out.println(" operation {");
//out.println(" "+ typeName +" t = ");
out.println(" U[x, y; t+1] = ");
out.print(" ");
int count = 1;
for(StencilPoint p : sp){
String aConst = ""+(count*7); // just a constant, per-sample value
String xs = (p.getX()>=0) ? ("+"+p.getX()) : (""+p.getX());
String ys = (p.getY()>=0) ? ("+"+p.getY()) : (""+p.getY());
out.print("U[x"+xs+", y"+ys+"; t] * "+ aConst);
if(count == sp.size() ) out.println(";"); // Note: <count> starts from 1
else out.print(" + ");
count++;
}
out.println(" } ");
out.println("} ");
}
// --- case bufNum > 1
else {
/*
* Note(Biagio): we do not support (i.e., we do no generate code pattern for) 2D stencil with more than one read buffer.
* The reason is that is very hard to have similar code working on Patus due to a nasty front-end bug.
* Nevertheless, there are no codes like that in Patus test benchmarks, and likely this is the reason such bug was unspotted so far.
*/
throw new RuntimeException("Stencil code generation of 2d code with more than one buffer is not currently supported.");
} // --- case bufNum > 1
}
/**
* Generate Patus' dsl code from an input 3D stencil pattern.
* The code is printed into a PrintStream.
*
* IMPORTANT NOTE: to overcome a nasty bug in Patus compiler with input stencil
* having more than one buffer, the code generator follow two different approaches
* 1. if <bufferNum> is 1, we have only one read buffer and one write buffer
* therefore we use the same buffer for input and output (overall only one)
* 2. if <bufferNum> is bigger than 1, we have 2 (or 3) read buffers and one write buffer
* therefore we use 2 (or 3) additional buffers, for a total of 3 (or 4).
*/
public void generate3DStencilCode(InputParams ip){
String typeName = (ip.getTypeSize()==0) ? "float" : "double";
StencilPattern sp = ip.getPattern();
out.println("/* auto-gen 3d stencil for pattern: ");
out.println(" "+ ip.getPattern().toString() );
// Note: input size is not encoded here (is not in InputParams), as it changes at execution time
out.println(" "+ ip.toEncodedString() );
out.println("*/");
final int bOffset = sp.getMaxRadius();
String bufferSize = "(0 .. x_max+"+bOffset+", 0 .. y_max+"+bOffset+", 0 .. z_max+"+bOffset+")";
String domainSize = "("+bOffset+" .. x_max, "+bOffset+" .. y_max, "+bOffset+" .. z_max)";
// --- special case: hyper-cube 3d
// Unfortunately, Patus compilation takes too long time (and often goes out-of-memory)
// for dense patterns such as 3d hypercube. A way to fix that in Patus is to use
// its multi-dimensional language feature (see tricubic).
if(sp.isCube()){
out.println("// code path 1");
out.println("stencil autogen3d (");
// arguments
out.println(" "+ typeName +" grid V" + bufferSize + ","); // in
for(int bN = 0; bN<ip.getBufferNum(); bN++){ // out
out.print(" const "+ typeName +" grid U" + bN + bufferSize);
if(bN != ip.getBufferNum()-1) out.println(",");
}
out.println(")");
out.println("{");
// body
int radius = sp.getCube();
String range = "-"+radius+".."+radius;
out.println(" domainsize = "+ domainSize + ";");
out.println();
out.println(" operation {");
for(int bN = 0; bN<ip.getBufferNum(); bN++){
out.println(" "+ typeName +" t" + bN +"["+ range +"] = {");
for(int k = -radius; k<=radius; k++){
String aConst = ""+(k*7); // just a constant, per-sample value
out.print(" "+aConst + " * U"+bN+"[x,y,z]");
if(k<radius) out.println(",");
else out.println();
}
out.println(" };");
}
// final gathering from multiple buffers
out.println("");
out.print (" V[x, y, z; t+1] = ");
if(ip.getBufferNum() == 1){
out.print("{ i="+range+" } sum(");
out.print("t0[i] * ");
out.println("V[x+i, y, z; t]);");
}
else if(ip.getBufferNum() == 2){
out.print("{ i="+range+", j="+range+" } sum(");
out.print("t0[i] * t1[j] * ");
out.println("V[x+i, y+j, z; t]);");
}
else if(ip.getBufferNum() == 3){
out.print("{ i="+range+", j="+range+", k="+range+" } sum(");
out.print("t0[i] * t1[j] * t2[k] * ");
out.println("V[x+i, y+j, z+k; t]);");
}
out.println();
out.println(" }");
out.println("}");
}
// if is not an hypercube, we generate the stencil point-by-point
// --- case bufNum is 1
else
if(ip.getBufferNum() == 1){
out.println("// code path 2");
out.println("stencil autogen3d ("+typeName +" grid U) {");
//out.println(" domainsize = (1 .. x_max, 1 .. y_max, 1 .. z_max);");
out.println(" domainsize = "+ domainSize + ";");
out.println();
out.println(" operation {");
out.println(" U[x, y, z; t+1] = ");
out.print( " ");
int count = 1;
for(StencilPoint p : sp){
String aConst = ""+(count*7); // just a constant, per-sample value
String xs = (p.getX()>=0) ? ("+"+p.getX()) : (""+p.getX());
String ys = (p.getY()>=0) ? ("+"+p.getY()) : (""+p.getY());
String zs = (p.getZ()>=0) ? ("+"+p.getZ()) : (""+p.getZ());
out.print("U[x"+xs+", y"+ys+", z"+zs+"; t] * "+ aConst);
if(count == sp.size() ) out.println(";"); // Note: <count> starts from 1
else out.print(" + ");
count++;
}
out.println(" } ");
out.println("} ");
}
// --- case bufNum > 1
else {
out.println("// code path 3");
// code-gen. similar to gradient, but with a temporary variable
out.println("stencil autogen3d (");
// arguments
out.println(" "+ typeName +" grid V" + bufferSize + ","); // in
for(int bN = 0; bN<ip.getBufferNum(); bN++){ // out
out.print(" const "+ typeName +" grid U" + bN + bufferSize);
if(bN != ip.getBufferNum()-1) out.println(",");
}
out.println(")");
out.println("{");
// body
out.println(" domainsize = "+ domainSize + ";");
out.println();
out.println(" operation {");
for(int bN = 0; bN<ip.getBufferNum(); bN++){
out.println(" "+ typeName +" t" + bN + " = ");
out.println(" (");
out.println(" ");
int count = 1;
for(StencilPoint p : sp){
String aConst = ""+(count*7); // just a constant, per-sample value
String xs = (p.getX()>=0) ? ("+"+p.getX()) : (""+p.getX());
String ys = (p.getY()>=0) ? ("+"+p.getY()) : (""+p.getY());
String zs = (p.getZ()>=0) ? ("+"+p.getZ()) : (""+p.getZ());
//out.print("U"+bN+"[x"+xs+", y"+ys+", z"+zs+"; t] * "+ aConst);
out.print("U"+bN+"[x"+xs+", y"+ys+", z"+zs+"] * "+ aConst);
if(count == sp.size() ) out.println("\n );"); // Note: <count> starts from 1
else out.print(" + ");
count++;
}
}
// gathering from the <bufferNum> buffers
out.print(" V[x, y, z; t] = ");
for(int bN = 0; bN<ip.getBufferNum(); bN++){
out.print(" t" + bN);
out.print( (bN==ip.getBufferNum()-1)?";":" + " );
}
out.println();
out.println(" }");
out.println("}");
}
out.println();
out.println();
}
/**
* Automatically generates stencil codes for all supported patterns, with different buffer num and
* up to a given pattern radius.
* @param args
* @throws IOException
*/
public static final void main(String args[]) throws IOException {
// parameters
final int maxPatternRadius = 3; // final version has to be from 1 to (maybe)3
//StencilPoint.MAX_STENCIL_SIZE = 10;//maxPatternRadius*2+1;
int genBufferNum[] = { 1, 3}; // { 1, 2, 3};
int maxTypeSize = 1; // type size is 0 for 32-bit types (float and int), or 1 for 64 (double)
System.out.println("Automatic stencil code generation in " + outputFolderString);
// Important note: (some) 3D kernels are trained with 1 and 3 buffers, but 2D kernels only 1 buffer (there is a problem with the Patus' backed compiler)
// // // 2D kernels here
System.out.println();
System.out.println("LaPlacian 2D");
for(int size = 1; size <= maxPatternRadius; size ++)
//for(int buffer = 1; buffer <= maxBufferNum; buffer ++)
for(int type = 0; type <= maxTypeSize; type ++)
{
int buffer = 1;
String stencilName = "autogen_laplace2d_s" + size + "_t" + type + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getLaPlacian2D(size);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate2DStencilCode(ip);
sg.close();
}
System.out.println();
System.out.println("Line 2D");
for(int size : new int[]{ 1, 3}) // for(int size = 1; size <= maxPatternRadius; size ++)
//for(int buffer = 1; buffer <= maxBufferNum; buffer *= 2)
for(int dim = 0; dim <= 1; dim++)
for(int type = 0; type <= maxTypeSize; type ++)
{
int buffer = 1;
String stencilName = "autogen_line2d_s" + size + "_t" + type + "_d" + dim + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getLine2D(size,dim);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate2DStencilCode(ip);
sg.close();
}
System.out.println();
System.out.println("Hypercube 2D");
for(int size : new int[]{ 1, 2, 3})
//for(int buffer = 1; buffer <= maxBufferNum; buffer *= 2)
for(int type = 0; type <= maxTypeSize; type ++)
{
final int buffer = 1;
String stencilName = "autogen_hypercube2d_s" + size + "_t" + type + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getHypercube2D(size);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate2DStencilCode(ip);
sg.close();
}
// // // 3D kernels here
System.out.println();
System.out.println("LaPlacian 3D");
for(int size = 1; size <= maxPatternRadius; size ++)
for(int buffer : new int[]{ 1, 2, 3})
for(int type = 0; type <= maxTypeSize; type ++)
{
// if(buffer == 3 && size >1) continue; // NOTE: unfortunately, we had memory issues with 3 buffers and many points with Patus onXeon E5
String stencilName = "autogen_laplace3d_s"+ size + "_b" + buffer + "_t" + type + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getLaPlacian3D(size);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate3DStencilCode(ip);
sg.close();
}
// Note: technically, some line3d codes are similar to line 2d
System.out.println();
System.out.println("Line 3D");
for(int size : new int[]{ 1}) // for(int size = 1; size <= maxPatternRadius; size ++)
// for(int buffer : genBufferNum)
for(int dim = 0; dim <= 2; dim++)
for(int type = 0; type <= maxTypeSize; type ++)
{
final int buffer = 1;
String stencilName = "autogen_line3d_s" + size + "_b" + buffer + "_t" + type + "_d" + dim + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getLine3D(size,dim);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate3DStencilCode(ip);
sg.close();
}
System.out.println();
System.out.println("Hyperplane 3D");
for(int size : new int[]{ 1, 2}) // for(int size = 1; size <= maxPatternRadius; size ++)
//for(int buffer : genBufferNum)
for(int dim = 0; dim <= 2; dim++)
for(int type = 0; type <= maxTypeSize; type ++)
{
final int buffer = 1;
String stencilName = "autogen_hyperplane3d_s" + size + "_b" + buffer + "_t" + type + "_d" + dim + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getHyperplane3D(size, dim);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate3DStencilCode(ip);
sg.close();
}
System.out.println();
System.out.println("Hypercube 3D");
for(int size : new int[]{ 1, 2}) //for(int size = 1; size <= maxPatternRadius; size ++)
for(int buffer : genBufferNum)
for(int type = 0; type <= maxTypeSize; type ++)
{
if(size == 3 && buffer == 3) continue; // NOTE: unfortunately, this configuration had memory issues on Patus/Xeon E5
String stencilName = "autogen_hypercube3d_s" + size + "_b" + buffer + "_t" + type + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getHypercube3D(size);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate3DStencilCode(ip);
sg.close();
}
System.out.println();
System.out.println("Stencil kernels generated into the folder: " + outputFolder.getAbsolutePath());
System.out.println();
}
}
| tune/stencil_tune/src/stenciltune/StencilGenerator.java | package stenciltune;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
/**
* Automatic generation of stencil patterns and stencil code.
* Each pattern is a collection of points (2d or 3d) following common stencil pattern,
* such as Laplacian, hypercube, hyperplane and lines.
* Additional information about feature encoding is in the file feature_encoding.txt.
* @author Biagio
*/
public class StencilGenerator {
public static String outputFolderString = "temp/ml_stencil_code";
public static File outputFolder;
/* static initialization block */
static {
// creating an output dir
outputFolder = new File(outputFolderString);
if(outputFolder.mkdirs()){
System.err.println("Error while creating the autogen output folder: " + outputFolder);
}
}
private PrintStream out;
public StencilGenerator(){
this.out = System.out;
}
public StencilGenerator(PrintStream ps){
this.out = ps;
}
public StencilGenerator(String stencilName) throws IOException {
File stencilFile = new File(outputFolder, stencilName);
stencilFile.createNewFile();
this.out = new PrintStream(stencilFile);
}
public void close(){
this.out.close();
}
/**
*
*
**W** LaPlacian
*
*
*/
public StencilPattern getLaPlacian2D(int size){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
sp.add(new Point2D(0, 0));
for(int i= -size; i<=size; i++)
if(i!=0)
sp.add(new Point2D( i, 0));
for(int i= -size; i<=size; i++)
if(i!=0)
sp.add(new Point2D( 0, i));
sp.sort();
return sp;
}
public StencilPattern getLaPlacian3D(int size){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
sp.add(new Point3D(0, 0, 0));
for(int i= -size; i<=size; i++)
if(i!=0)
sp.add(new Point3D( i, 0, 0));
for(int i= -size; i<=size; i++)
if(i!=0)
sp.add(new Point3D( 0, i, 0));
for(int i= -size; i<=size; i++)
if(i!=0)
sp.add(new Point3D( 0, 0, i));
sp.sort();
return sp;
}
/**
*
*
W Line (spanning only on one dimension)
*
*
*/
public StencilPattern getLine2D(int size, int dim){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
sp.add(new Point2D(0, 0));
if(dim == 0)
for(int i=1; i<=size; i++){
sp.add(new Point2D( i, 0));
sp.add(new Point2D(-i, 0));
}
else
if (dim == 1)
for(int i=1; i<=size; i++){
sp.add(new Point2D( 0, i));
sp.add(new Point2D( 0,-i));
}
else throw new RuntimeException("Dimension not supported (only 0 and 1) instead of "+dim);
sp.sort();
return sp;
}
public StencilPattern getLine3D(int size, int dim){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
sp.add(new Point3D(0, 0,0));
switch(dim){
case 0:
for(int i=1; i<=size; i++){
sp.add(new Point3D( i, 0, 0));
sp.add(new Point3D(-i, 0, 0));
}
break;
case 1:
for(int i=1; i<=size; i++){
sp.add(new Point3D( 0, i, 0));
sp.add(new Point3D( 0,-i, 0));
}
break;
case 2:
for(int i=1; i<=size; i++){
sp.add(new Point3D( 0, 0, i));
sp.add(new Point3D( 0, 0,-i));
}
break;
default:
throw new RuntimeException("Dimension not supported (only 0, 1 and 2) instead of "+dim);
}
sp.sort();
return sp;
}
/**
*
*
W Hyper-plane (only 3d, spans one 2 of 3 dimensions)
*
*
*/
/* dim indicates the free dimension */
public StencilPattern getHyperplane3D(int size, int dim){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
// sp.add(new Point3D(0, 0, 0));
switch(dim){
case 0:
for(int i=-size; i<=size; i++)
for(int j=-size; j<=size; j++)
{
sp.add(new Point3D( i, j, 0));
}
break;
case 1:
for(int i=-size; i<=size; i++)
for(int j=-size; j<=size; j++)
{
sp.add(new Point3D( i, 0, j));
}
break;
case 2:
for(int i=-size; i<=size; i++)
for(int j=-size; j<=size; j++)
{
sp.add(new Point3D( 0, i, j));
}
break;
default:
throw new RuntimeException("Dimension not supported (only 0, 1 and 2) instead of "+dim);
}
sp.sort();
return sp;
}
/**
*****
*****
**W** Hyper-cube
*****
*****
*/
public StencilPattern getHypercube2D(int size){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
for(int i= -size; i<=size; i++)
for(int j= -size; j<=size; j++)
{
sp.add(new Point2D( i, j));
}
sp.sort();
return sp;
}
public StencilPattern getHypercube3D(int size){
if(size == 0) throw new RuntimeException("Size has to be >0");
StencilPattern sp = new StencilPattern();
for(int i= -size; i<=size; i++)
for(int j= -size; j<=size; j++)
for(int k= -size; k<=size; k++)
{
sp.add(new Point3D( i, j, k));
}
sp.sort();
return sp;
}
/**
* Generate Patus' DSL code from an input 2D stencil pattern.
* The code is printed into a PrintStream.
*
* IMPORTANT NOTE: current implementation only supports <bufferNum> = 1
*/
public void generate2DStencilCode(InputParams ip){
String typeName = (ip.getTypeSize()==0) ? "float" : "double";
StencilPattern sp = ip.getPattern();
out.println("/* auto-gen 2d stencil for pattern: ");
out.println(" "+ ip.getPattern().toString() );
// Note: input size is not encoded here (is not in InputParams), as it changes at execution time
out.println(" "+ ip.toEncodedString() );
out.println("*/");
out.println("stencil autogen2d (");
// --- case bufNum is 1
if(ip.getBufferNum() == 1){
// arguments
out.println(" "+ typeName +" grid U) {");
// body
out.println(" domainsize = ("+sp.getMaxRadius()+" .. width-"+sp.getMaxRadius()+", "+sp.getMaxRadius()+" .. height-"+sp.getMaxRadius()+");");
out.println();
out.println(" operation {");
//out.println(" "+ typeName +" t = ");
out.println(" U[x, y; t+1] = ");
out.print(" ");
int count = 1;
for(StencilPoint p : sp){
String aConst = ""+(count*7); // just a constant, per-sample value
String xs = (p.getX()>=0) ? ("+"+p.getX()) : (""+p.getX());
String ys = (p.getY()>=0) ? ("+"+p.getY()) : (""+p.getY());
out.print("U[x"+xs+", y"+ys+"; t] * "+ aConst);
if(count == sp.size() ) out.println(";"); // Note: <count> starts from 1
else out.print(" + ");
count++;
}
out.println(" } ");
out.println("} ");
}
// --- case bufNum > 1
else {
/*
* Note(Biagio): we do not support (i.e., we do no generate code pattern for) 2D stencil with more than one read buffer.
* The reason is that is very hard to have similar code working on Patus due to a nasty front-end bug.
* Nevertheless, there are no codes like that in Patus test benchmarks, and likely this is the reason such bug was unspotted so far.
*/
throw new RuntimeException("Stencil code generation of 2d code with more than one buffer is not currently supported.");
} // --- case bufNum > 1
}
/**
* Generate Patus' dsl code from an input 3D stencil pattern.
* The code is printed into a PrintStream.
*
* IMPORTANT NOTE: to overcome a nasty bug in Patus compiler with input stencil
* having more than one buffer, the code generator follow two different approaches
* 1. if <bufferNum> is 1, we have only one read buffer and one write buffer
* therefore we use the same buffer for input and output (overall only one)
* 2. if <bufferNum> is bigger than 1, we have 2 (or 3) read buffers and one write buffer
* therefore we use 2 (or 3) additional buffers, for a total of 3 (or 4).
*/
public void generate3DStencilCode(InputParams ip){
String typeName = (ip.getTypeSize()==0) ? "float" : "double";
StencilPattern sp = ip.getPattern();
out.println("/* auto-gen 3d stencil for pattern: ");
out.println(" "+ ip.getPattern().toString() );
// Note: input size is not encoded here (is not in InputParams), as it changes at execution time
out.println(" "+ ip.toEncodedString() );
out.println("*/");
final int bOffset = sp.getMaxRadius();
String bufferSize = "(0 .. x_max+"+bOffset+", 0 .. y_max+"+bOffset+", 0 .. z_max+"+bOffset+")";
String domainSize = "("+bOffset+" .. x_max, "+bOffset+" .. y_max, "+bOffset+" .. z_max)";
// --- special case: hyper-cube 3d
// Unfortunately, Patus compilation takes too long time (and often goes out-of-memory)
// for dense patterns such as 3d hypercube. A way to fix that in Patus is to use
// its multi-dimensional language feature (see tricubic).
if(sp.isCube()){
out.println("// code path 1");
out.println("stencil autogen3d (");
// arguments
out.println(" "+ typeName +" grid V" + bufferSize + ","); // in
for(int bN = 0; bN<ip.getBufferNum(); bN++){ // out
out.print(" const "+ typeName +" grid U" + bN + bufferSize);
if(bN != ip.getBufferNum()-1) out.println(",");
}
out.println(")");
out.println("{");
// body
int radius = sp.getCube();
String range = "-"+radius+".."+radius;
out.println(" domainsize = "+ domainSize + ";");
out.println();
out.println(" operation {");
for(int bN = 0; bN<ip.getBufferNum(); bN++){
out.println(" "+ typeName +" t" + bN +"["+ range +"] = {");
for(int k = -radius; k<=radius; k++){
String aConst = ""+(k*7); // just a constant, per-sample value
out.print(" "+aConst + " * U"+bN+"[x,y,z]");
if(k<radius) out.println(",");
else out.println();
}
out.println(" };");
}
// final gathering from multiple buffers
out.println("");
out.print (" V[x, y, z; t+1] = ");
if(ip.getBufferNum() == 1){
out.print("{ i="+range+" } sum(");
out.print("t0[i] * ");
out.println("V[x+i, y, z; t]);");
}
else if(ip.getBufferNum() == 2){
out.print("{ i="+range+", j="+range+" } sum(");
out.print("t0[i] * t1[j] * ");
out.println("V[x+i, y+j, z; t]);");
}
else if(ip.getBufferNum() == 3){
out.print("{ i="+range+", j="+range+", k="+range+" } sum(");
out.print("t0[i] * t1[j] * t2[k] * ");
out.println("V[x+i, y+j, z+k; t]);");
}
out.println();
out.println(" }");
out.println("}");
}
// if is not an hypercube, we generate the stencil point-by-point
// --- case bufNum is 1
else
if(ip.getBufferNum() == 1){
out.println("// code path 2");
out.println("stencil autogen3d ("+typeName +" grid U) {");
//out.println(" domainsize = (1 .. x_max, 1 .. y_max, 1 .. z_max);");
out.println(" domainsize = "+ domainSize + ";");
out.println();
out.println(" operation {");
out.println(" U[x, y, z; t+1] = ");
out.print( " ");
int count = 1;
for(StencilPoint p : sp){
String aConst = ""+(count*7); // just a constant, per-sample value
String xs = (p.getX()>=0) ? ("+"+p.getX()) : (""+p.getX());
String ys = (p.getY()>=0) ? ("+"+p.getY()) : (""+p.getY());
String zs = (p.getZ()>=0) ? ("+"+p.getZ()) : (""+p.getZ());
out.print("U[x"+xs+", y"+ys+", z"+zs+"; t] * "+ aConst);
if(count == sp.size() ) out.println(";"); // Note: <count> starts from 1
else out.print(" + ");
count++;
}
out.println(" } ");
out.println("} ");
}
// --- case bufNum > 1
else {
out.println("// code path 3");
// code-gen. similar to gradient, but with a temporary variable
out.println("stencil autogen3d (");
// arguments
out.println(" "+ typeName +" grid V" + bufferSize + ","); // in
for(int bN = 0; bN<ip.getBufferNum(); bN++){ // out
out.print(" const "+ typeName +" grid U" + bN + bufferSize);
if(bN != ip.getBufferNum()-1) out.println(",");
}
out.println(")");
out.println("{");
// body
out.println(" domainsize = "+ domainSize + ";");
out.println();
out.println(" operation {");
for(int bN = 0; bN<ip.getBufferNum(); bN++){
out.println(" "+ typeName +" t" + bN + " = ");
out.println(" (");
out.println(" ");
int count = 1;
for(StencilPoint p : sp){
String aConst = ""+(count*7); // just a constant, per-sample value
String xs = (p.getX()>=0) ? ("+"+p.getX()) : (""+p.getX());
String ys = (p.getY()>=0) ? ("+"+p.getY()) : (""+p.getY());
String zs = (p.getZ()>=0) ? ("+"+p.getZ()) : (""+p.getZ());
//out.print("U"+bN+"[x"+xs+", y"+ys+", z"+zs+"; t] * "+ aConst);
out.print("U"+bN+"[x"+xs+", y"+ys+", z"+zs+"] * "+ aConst);
if(count == sp.size() ) out.println("\n );"); // Note: <count> starts from 1
else out.print(" + ");
count++;
}
}
// gathering from the <bufferNum> buffers
out.print(" V[x, y, z; t] = ");
for(int bN = 0; bN<ip.getBufferNum(); bN++){
out.print(" t" + bN);
out.print( (bN==ip.getBufferNum()-1)?";":" + " );
}
out.println();
out.println(" }");
out.println("}");
}
out.println();
out.println();
}
/**
* Automatically generates stencil codes for all supported patterns, with different buffer num and
* up to a given pattern radius.
* @param args
* @throws IOException
*/
public static final void main(String args[]) throws IOException {
// parameters
final int maxPatternRadius = 3; // final version has to be from 1 to (maybe)3
//StencilPoint.MAX_STENCIL_SIZE = 10;//maxPatternRadius*2+1;
int genBufferNum[] = { 1, 3}; // { 1, 2, 3};
int maxTypeSize = 1; // type size is 0 for 3d-bit types (float and int), or 1 for 64 (double)
System.out.println("Automatic stencil code generation in " + outputFolderString);
// Important note: (some) 3D kernels are trained with 1 and 3 buffers, but 2D kernels only 1 buffer (there is a problem with the Patus' backed compiler)
// // // 2D kernels here
System.out.println();
System.out.println("LaPlacian 2D");
for(int size = 1; size <= maxPatternRadius; size ++)
//for(int buffer = 1; buffer <= maxBufferNum; buffer ++)
for(int type = 0; type <= maxTypeSize; type ++)
{
int buffer = 1;
String stencilName = "autogen_laplace2d_s" + size + "_t" + type + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getLaPlacian2D(size);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate2DStencilCode(ip);
sg.close();
}
System.out.println();
System.out.println("Line 2D");
for(int size : new int[]{ 1, 3}) // for(int size = 1; size <= maxPatternRadius; size ++)
//for(int buffer = 1; buffer <= maxBufferNum; buffer *= 2)
for(int dim = 0; dim <= 1; dim++)
for(int type = 0; type <= maxTypeSize; type ++)
{
int buffer = 1;
String stencilName = "autogen_line2d_s" + size + "_t" + type + "_d" + dim + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getLine2D(size,dim);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate2DStencilCode(ip);
sg.close();
}
System.out.println();
System.out.println("Hypercube 2D");
for(int size : new int[]{ 1, 2, 3})
//for(int buffer = 1; buffer <= maxBufferNum; buffer *= 2)
for(int type = 0; type <= maxTypeSize; type ++)
{
final int buffer = 1;
String stencilName = "autogen_hypercube2d_s" + size + "_t" + type + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getHypercube2D(size);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate2DStencilCode(ip);
sg.close();
}
// // // 3D kernels here
System.out.println();
System.out.println("LaPlacian 3D");
for(int size = 1; size <= maxPatternRadius; size ++)
for(int buffer : new int[]{ 1, 2, 3})
for(int type = 0; type <= maxTypeSize; type ++)
{
// if(buffer == 3 && size >1) continue; // NOTE: unfortunately, we had memory issues with 3 buffers and many points with Patus onXeon E5
String stencilName = "autogen_laplace3d_s"+ size + "_b" + buffer + "_t" + type + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getLaPlacian3D(size);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate3DStencilCode(ip);
sg.close();
}
// Note: technically, some line3d codes are similar to line 2d
System.out.println();
System.out.println("Line 3D");
for(int size : new int[]{ 1}) // for(int size = 1; size <= maxPatternRadius; size ++)
// for(int buffer : genBufferNum)
for(int dim = 0; dim <= 2; dim++)
for(int type = 0; type <= maxTypeSize; type ++)
{
final int buffer = 1;
String stencilName = "autogen_line3d_s" + size + "_b" + buffer + "_t" + type + "_d" + dim + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getLine3D(size,dim);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate3DStencilCode(ip);
sg.close();
}
System.out.println();
System.out.println("Hyperplane 3D");
for(int size : new int[]{ 1, 2}) // for(int size = 1; size <= maxPatternRadius; size ++)
//for(int buffer : genBufferNum)
for(int dim = 0; dim <= 2; dim++)
for(int type = 0; type <= maxTypeSize; type ++)
{
final int buffer = 1;
String stencilName = "autogen_hyperplane3d_s" + size + "_b" + buffer + "_t" + type + "_d" + dim + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getHyperplane3D(size, dim);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate3DStencilCode(ip);
sg.close();
}
System.out.println();
System.out.println("Hypercube 3D");
for(int size : new int[]{ 1, 2}) //for(int size = 1; size <= maxPatternRadius; size ++)
for(int buffer : genBufferNum)
for(int type = 0; type <= maxTypeSize; type ++)
{
if(size == 3 && buffer == 3) continue; // NOTE: unfortunately, this configuration had memory issues on Patus/Xeon E5
String stencilName = "autogen_hypercube3d_s" + size + "_b" + buffer + "_t" + type + ".stc";
StencilGenerator sg = new StencilGenerator(stencilName);
StencilPattern sp = sg.getHypercube3D(size);
InputParams ip = new InputParams(sp, buffer, type);
System.out.print(" " + ip + " / normalized: " + ip.toEncodedString());
sg.generate3DStencilCode(ip);
sg.close();
}
System.out.println();
System.out.println("Stencil kernels generated into the folder: " + outputFolder.getAbsolutePath());
System.out.println();
}
}
| trainign code generator: forgot a file
| tune/stencil_tune/src/stenciltune/StencilGenerator.java | trainign code generator: forgot a file | <ide><path>une/stencil_tune/src/stenciltune/StencilGenerator.java
<ide> //StencilPoint.MAX_STENCIL_SIZE = 10;//maxPatternRadius*2+1;
<ide>
<ide> int genBufferNum[] = { 1, 3}; // { 1, 2, 3};
<del> int maxTypeSize = 1; // type size is 0 for 3d-bit types (float and int), or 1 for 64 (double)
<add> int maxTypeSize = 1; // type size is 0 for 32-bit types (float and int), or 1 for 64 (double)
<ide>
<ide>
<ide> System.out.println("Automatic stencil code generation in " + outputFolderString); |
|
Java | apache-2.0 | 43ba8a388d2a1f08a78668243e54896ca2807a99 | 0 | apache/commons-jexl,apache/commons-jexl,apache/commons-jexl | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.jexl3;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.jexl3.internal.Script;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests around asynchronous script execution and interrupts.
*/
@SuppressWarnings({"UnnecessaryBoxing", "AssertEqualsBetweenInconvertibleTypes"})
public class ScriptCallableTest extends JexlTestCase {
//Logger LOGGER = Logger.getLogger(VarTest.class.getName());
public ScriptCallableTest() {
super("ScriptCallableTest");
}
@Test
public void testFuture() throws Exception {
JexlScript e = JEXL.createScript("while(true);");
FutureTask<Object> future = new FutureTask<Object>(e.callable(null));
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(future);
Object t = 42;
try {
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
// ok, ignore
future.cancel(true);
} finally {
executor.shutdown();
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
}
@Test
public void testCallableCancel() throws Exception {
final Semaphore latch = new Semaphore(0);
JexlContext ctxt = new MapContext();
ctxt.set("latch", latch);
JexlScript e = JEXL.createScript("latch.acquire(1); while(true);");
final Script.Callable c = (Script.Callable) e.callable(ctxt);
Object t = 42;
Callable<Object> kc = new Callable<Object>() {
@Override
public Object call() throws Exception {
latch.release();
return c.cancel();
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<?> future = executor.submit(c);
Future<?> kfc = executor.submit(kc);
try {
Assert.assertTrue((Boolean) kfc.get());
t = future.get();
Assert.fail("should have been cancelled");
} catch (ExecutionException xexec) {
// ok, ignore
Assert.assertTrue(xexec.getCause() instanceof JexlException.Cancel);
} finally {
executor.shutdown();
}
Assert.assertTrue(c.isCancelled());
}
@Test
public void testCallableTimeout() throws Exception {
JexlScript e = JEXL.createScript("while(true);");
Callable<Object> c = e.callable(null);
Object t = 42;
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(c);
try {
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
// ok, ignore
future.cancel(true);
} finally {
executor.shutdown();
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
}
@Test
public void testCallableClosure() throws Exception {
JexlScript e = JEXL.createScript("function(t) {while(t);}");
Callable<Object> c = e.callable(null, Boolean.TRUE);
Object t = 42;
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(c);
try {
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
// ok, ignore
future.cancel(true);
} finally {
executor.shutdown();
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
}
public static class TestContext extends MapContext implements JexlContext.NamespaceResolver {
@Override
public Object resolveNamespace(String name) {
return name == null ? this : null;
}
public int wait(int s) throws InterruptedException {
Thread.sleep(1000 * s);
return s;
}
public int waitInterrupt(int s) {
try {
Thread.sleep(1000 * s);
return s;
} catch (InterruptedException xint) {
Thread.currentThread().interrupt();
}
return -1;
}
public int runForever() {
while (true) {
if (Thread.currentThread().isInterrupted()) {
break;
}
}
return 1;
}
public int interrupt() throws InterruptedException {
Thread.currentThread().interrupt();
return 42;
}
public void sleep(long millis) throws InterruptedException {
try {
Thread.sleep(millis);
} catch (InterruptedException xint) {
throw xint;
}
}
public int hangs(Object t) {
return 1;
}
}
@Test
public void testNoWait() throws Exception {
JexlScript e = JEXL.createScript("wait(0)");
Callable<Object> c = e.callable(new TestContext());
ExecutorService executor = Executors.newFixedThreadPool(1);
try {
Future<?> future = executor.submit(c);
Object t = future.get(2, TimeUnit.SECONDS);
Assert.assertTrue(future.isDone());
Assert.assertEquals(0, t);
} finally {
executor.shutdown();
}
}
@Test
public void testWait() throws Exception {
JexlScript e = JEXL.createScript("wait(1)");
Callable<Object> c = e.callable(new TestContext());
ExecutorService executor = Executors.newFixedThreadPool(1);
try {
Future<?> future = executor.submit(c);
Object t = future.get(2, TimeUnit.SECONDS);
Assert.assertEquals(1, t);
} finally {
executor.shutdown();
}
}
@Test
public void testCancelWait() throws Exception {
JexlScript e = JEXL.createScript("wait(10)");
Callable<Object> c = e.callable(new TestContext());
ExecutorService executor = Executors.newFixedThreadPool(1);
try {
Future<?> future = executor.submit(c);
Object t = 42;
try {
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
// ok, ignore
future.cancel(true);
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
} finally {
executor.shutdown();
}
}
@Test
public void testCancelWaitInterrupt() throws Exception {
JexlScript e = JEXL.createScript("waitInterrupt(42)");
Callable<Object> c = e.callable(new TestContext());
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(c);
Object t = 42;
try {
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
// ok, ignore
future.cancel(true);
} finally {
executor.shutdown();
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
}
@Test
public void testCancelForever() throws Exception {
final Semaphore latch = new Semaphore(0);
JexlContext ctxt = new TestContext();
ctxt.set("latch", latch);
JexlScript e = JEXL.createScript("runForever()");
Callable<Object> c = e.callable(ctxt);
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(c);
Object t = 42;
try {
latch.release();
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
// ok, ignore
future.cancel(true);
} finally {
executor.shutdown();
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
}
@Test
public void testCancelLoopWait() throws Exception {
JexlScript e = JEXL.createScript("while (true) { wait(10) }");
Callable<Object> c = e.callable(new TestContext());
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(c);
Object t = 42;
try {
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
future.cancel(true);
} finally {
executor.shutdown();
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
}
@Test
public void testInterruptVerboseStrict() throws Exception {
runInterrupt(new JexlBuilder().silent(false).strict(true).create());
}
@Test
public void testInterruptVerboseLenient() throws Exception {
runInterrupt(new JexlBuilder().silent(false).strict(false).create());
}
@Test
public void testInterruptSilentStrict() throws Exception {
runInterrupt(new JexlBuilder().silent(true).strict(true).create());
}
@Test
public void testInterruptSilentLenient() throws Exception {
runInterrupt(new JexlBuilder().silent(true).strict(false).create());
}
@Test
public void testInterruptCancellable() throws Exception {
runInterrupt(new JexlBuilder().silent(true).strict(true).cancellable(true).create());
}
/**
* Redundant test with previous ones but impervious to JEXL engine configuation.
* @param silent silent engine flag
* @param strict strict (aka not lenient) engine flag
* @throws Exception if there is a regression
*/
private void runInterrupt(JexlEngine jexl) throws Exception {
ExecutorService exec = Executors.newFixedThreadPool(2);
try {
JexlContext ctxt = new TestContext();
// run an interrupt
JexlScript sint = jexl.createScript("interrupt(); return 42");
Object t = null;
Script.Callable c = (Script.Callable) sint.callable(ctxt);
try {
t = c.call();
if (c.isCancellable()) {
Assert.fail("should have thrown a Cancel");
}
} catch (JexlException.Cancel xjexl) {
if (!c.isCancellable()) {
Assert.fail("should not have thrown " + xjexl);
}
}
Assert.assertTrue(c.isCancelled());
Assert.assertNotEquals(42, t);
// self interrupt
Future<Object> f = null;
c = (Script.Callable) sint.callable(ctxt);
try {
f = exec.submit(c);
t = f.get();
if (c.isCancellable()) {
Assert.fail("should have thrown a Cancel");
}
} catch (ExecutionException xexec) {
if (!c.isCancellable()) {
Assert.fail("should not have thrown " + xexec);
}
}
Assert.assertTrue(c.isCancelled());
Assert.assertNotEquals(42, t);
// timeout a sleep
JexlScript ssleep = jexl.createScript("sleep(30000); return 42");
try {
f = exec.submit(ssleep.callable(ctxt));
t = f.get(100L, TimeUnit.MILLISECONDS);
Assert.fail("should timeout");
} catch (TimeoutException xtimeout) {
if (f != null) {
f.cancel(true);
}
}
Assert.assertNotEquals(42, t);
// cancel a sleep
try {
final Future<Object> fc = exec.submit(ssleep.callable(ctxt));
Runnable cancels = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(200L);
} catch (Exception xignore) {
}
fc.cancel(true);
}
};
exec.submit(cancels);
t = fc.get();
Assert.fail("should be cancelled");
} catch (CancellationException xexec) {
// this is the expected result
}
// timeout a while(true)
JexlScript swhile = jexl.createScript("while(true); return 42");
try {
f = exec.submit(swhile.callable(ctxt));
t = f.get(100L, TimeUnit.MILLISECONDS);
Assert.fail("should timeout");
} catch (TimeoutException xtimeout) {
if (f != null) {
f.cancel(true);
}
}
Assert.assertNotEquals(42, t);
// cancel a while(true)
try {
final Future<Object> fc = exec.submit(swhile.callable(ctxt));
Runnable cancels = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(200L);
} catch (Exception xignore) {
}
fc.cancel(true);
}
};
exec.submit(cancels);
t = fc.get();
Assert.fail("should be cancelled");
} catch (CancellationException xexec) {
// this is the expected result
}
Assert.assertNotEquals(42, t);
} finally {
exec.shutdown();
}
}
@Test
public void testHangs() throws Exception {
JexlScript e = JEXL.createScript("hangs()");
Callable<Object> c = e.callable(new TestContext());
ExecutorService executor = Executors.newFixedThreadPool(1);
try {
Future<?> future = executor.submit(c);
Object t = future.get(1, TimeUnit.SECONDS);
Assert.fail("hangs should not be solved");
} catch(ExecutionException xexec) {
Assert.assertTrue(xexec.getCause() instanceof JexlException.Method);
} finally {
executor.shutdown();
}
}
}
| src/test/java/org/apache/commons/jexl3/ScriptCallableTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.jexl3;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.jexl3.internal.Script;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests around asynchronous script execution and interrupts.
*/
@SuppressWarnings({"UnnecessaryBoxing", "AssertEqualsBetweenInconvertibleTypes"})
public class ScriptCallableTest extends JexlTestCase {
//Logger LOGGER = Logger.getLogger(VarTest.class.getName());
public ScriptCallableTest() {
super("ScriptCallableTest");
}
@Test
public void testFuture() throws Exception {
JexlScript e = JEXL.createScript("while(true);");
FutureTask<Object> future = new FutureTask<Object>(e.callable(null));
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(future);
Object t = 42;
try {
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
// ok, ignore
future.cancel(true);
} finally {
executor.shutdown();
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
}
@Test
public void testCallableCancel() throws Exception {
final Semaphore latch = new Semaphore(0);
JexlContext ctxt = new MapContext();
ctxt.set("latch", latch);
JexlScript e = JEXL.createScript("latch.acquire(1); while(true);");
final Script.Callable c = (Script.Callable) e.callable(ctxt);
Object t = 42;
Callable<Object> kc = new Callable<Object>() {
@Override
public Object call() throws Exception {
latch.release();
return c.cancel();
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<?> future = executor.submit(c);
Future<?> kfc = executor.submit(kc);
try {
Assert.assertTrue((Boolean) kfc.get());
t = future.get();
Assert.fail("should have been cancelled");
} catch (ExecutionException xexec) {
// ok, ignore
Assert.assertTrue(xexec.getCause() instanceof JexlException.Cancel);
} finally {
executor.shutdown();
}
Assert.assertTrue(c.isCancelled());
}
@Test
public void testCallableTimeout() throws Exception {
JexlScript e = JEXL.createScript("while(true);");
Callable<Object> c = e.callable(null);
Object t = 42;
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(c);
try {
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
// ok, ignore
future.cancel(true);
} finally {
executor.shutdown();
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
}
@Test
public void testCallableClosure() throws Exception {
JexlScript e = JEXL.createScript("function(t) {while(t);}");
Callable<Object> c = e.callable(null, Boolean.TRUE);
Object t = 42;
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(c);
try {
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
// ok, ignore
future.cancel(true);
} finally {
executor.shutdown();
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
}
public static class TestContext extends MapContext implements JexlContext.NamespaceResolver {
@Override
public Object resolveNamespace(String name) {
return name == null ? this : null;
}
public int wait(int s) throws InterruptedException {
Thread.sleep(1000 * s);
return s;
}
public int waitInterrupt(int s) {
try {
Thread.sleep(1000 * s);
return s;
} catch (InterruptedException xint) {
Thread.currentThread().interrupt();
}
return -1;
}
public int runForever() {
while (true) {
if (Thread.currentThread().isInterrupted()) {
break;
}
}
return 1;
}
public int interrupt() throws InterruptedException {
Thread.currentThread().interrupt();
return 42;
}
public void sleep(long millis) throws InterruptedException {
try {
Thread.sleep(millis);
} catch (InterruptedException xint) {
throw xint;
}
}
public int hangs(Object t) {
return 1;
}
}
@Test
public void testNoWait() throws Exception {
JexlScript e = JEXL.createScript("wait(0)");
Callable<Object> c = e.callable(new TestContext());
ExecutorService executor = Executors.newFixedThreadPool(1);
try {
Future<?> future = executor.submit(c);
Object t = future.get(2, TimeUnit.SECONDS);
Assert.assertTrue(future.isDone());
Assert.assertEquals(0, t);
} finally {
executor.shutdown();
}
}
@Test
public void testWait() throws Exception {
JexlScript e = JEXL.createScript("wait(1)");
Callable<Object> c = e.callable(new TestContext());
ExecutorService executor = Executors.newFixedThreadPool(1);
try {
Future<?> future = executor.submit(c);
Object t = future.get(2, TimeUnit.SECONDS);
Assert.assertEquals(1, t);
} finally {
executor.shutdown();
}
}
@Test
public void testCancelWait() throws Exception {
JexlScript e = JEXL.createScript("wait(10)");
Callable<Object> c = e.callable(new TestContext());
ExecutorService executor = Executors.newFixedThreadPool(1);
try {
Future<?> future = executor.submit(c);
Object t = 42;
try {
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
// ok, ignore
future.cancel(true);
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
} finally {
executor.shutdown();
}
}
@Test
public void testCancelWaitInterrupt() throws Exception {
JexlScript e = JEXL.createScript("waitInterrupt(42)");
Callable<Object> c = e.callable(new TestContext());
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(c);
Object t = 42;
try {
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
// ok, ignore
future.cancel(true);
} finally {
executor.shutdown();
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
}
@Test
public void testCancelForever() throws Exception {
final Semaphore latch = new Semaphore(0);
JexlContext ctxt = new TestContext();
ctxt.set("latch", latch);
JexlScript e = JEXL.createScript("runForever()");
Callable<Object> c = e.callable(ctxt);
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(c);
Object t = 42;
try {
latch.release();
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
// ok, ignore
future.cancel(true);
} finally {
executor.shutdown();
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
}
@Test
public void testCancelLoopWait() throws Exception {
JexlScript e = JEXL.createScript("while (true) { wait(10) }");
Callable<Object> c = e.callable(new TestContext());
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(c);
Object t = 42;
try {
t = future.get(100, TimeUnit.MILLISECONDS);
Assert.fail("should have timed out");
} catch (TimeoutException xtimeout) {
future.cancel(true);
} finally {
executor.shutdown();
}
Assert.assertTrue(future.isCancelled());
Assert.assertEquals(42, t);
}
@Test
public void testInterruptVerboseStrict() throws Exception {
runInterrupt(new JexlBuilder().silent(false).strict(true).create());
}
@Test
public void testInterruptVerboseLenient() throws Exception {
runInterrupt(new JexlBuilder().silent(false).strict(false).create());
}
@Test
public void testInterruptSilentStrict() throws Exception {
runInterrupt(new JexlBuilder().silent(true).strict(true).create());
}
@Test
public void testInterruptSilentLenient() throws Exception {
runInterrupt(new JexlBuilder().silent(true).strict(false).create());
}
@Test
public void testInterruptCancellable() throws Exception {
runInterrupt(new JexlBuilder().silent(true).strict(true).cancellable(true).create());
}
/**
* Redundant test with previous ones but impervious to JEXL engine configuation.
* @param silent silent engine flag
* @param strict strict (aka not lenient) engine flag
* @throws Exception if there is a regression
*/
private void runInterrupt(JexlEngine jexl) throws Exception {
ExecutorService exec = Executors.newFixedThreadPool(2);
try {
JexlContext ctxt = new TestContext();
// run an interrupt
JexlScript sint = jexl.createScript("interrupt(); return 42");
Object t = null;
Script.Callable c = (Script.Callable) sint.callable(ctxt);
try {
t = c.call();
if (c.isCancellable()) {
Assert.fail("should have thrown a Cancel");
}
} catch (JexlException.Cancel xjexl) {
if (!c.isCancellable()) {
Assert.fail("should not have thrown " + xjexl);
}
}
Assert.assertTrue(c.isCancelled());
Assert.assertNotEquals(42, t);
// self interrupt
Future<Object> f = null;
c = (Script.Callable) sint.callable(ctxt);
try {
f = exec.submit(c);
t = f.get();
if (c.isCancellable()) {
Assert.fail("should have thrown a Cancel");
}
} catch (ExecutionException xexec) {
if (!c.isCancellable()) {
Assert.fail("should not have thrown " + xexec);
}
}
Assert.assertTrue(c.isCancelled());
Assert.assertNotEquals(42, t);
// timeout a sleep
JexlScript ssleep = jexl.createScript("sleep(30000); return 42");
try {
f = exec.submit(ssleep.callable(ctxt));
t = f.get(100L, TimeUnit.MILLISECONDS);
Assert.fail("should timeout");
} catch (TimeoutException xtimeout) {
if (f != null) {
f.cancel(true);
}
}
Assert.assertNotEquals(42, t);
// cancel a sleep
try {
final Future<Object> fc = exec.submit(ssleep.callable(ctxt));
Runnable cancels = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(200L);
} catch (Exception xignore) {
}
fc.cancel(true);
}
};
exec.submit(cancels);
t = fc.get();
Assert.fail("should be cancelled");
} catch (CancellationException xexec) {
// this is the expected result
}
// timeout a while(true)
JexlScript swhile = jexl.createScript("while(true); return 42");
try {
f = exec.submit(swhile.callable(ctxt));
t = f.get(100L, TimeUnit.MILLISECONDS);
Assert.fail("should timeout");
} catch (TimeoutException xtimeout) {
if (f != null) {
f.cancel(true);
}
}
Assert.assertNotEquals(42, t);
// cancel a while(true)
try {
final Future<Object> fc = exec.submit(swhile.callable(ctxt));
Runnable cancels = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(200L);
} catch (Exception xignore) {
}
fc.cancel(true);
}
};
exec.submit(cancels);
t = fc.get();
Assert.fail("should be cancelled");
} catch (CancellationException xexec) {
// this is the expected result
}
Assert.assertNotEquals(42, t);
} finally {
exec.shutdown();
}
}
@Test
public void testHangs() throws Exception {
JexlScript e = JEXL.createScript("hangs()");
Callable<Object> c = e.callable(new TestContext());
ExecutorService executor = Executors.newFixedThreadPool(1);
try {
Future<?> future = executor.submit(c);
Object t = future.get(1, TimeUnit.SECONDS);
Assert.fail("hangs should not be solved");
} catch(ExecutionException xexec) {
Assert.assertTrue(xexec.getCause() instanceof JexlException.Method);
} finally {
executor.shutdown();
}
}
}
| JEXL:
JEXL-205; check interruption status within loop to detect cancellation
git-svn-id: 4652571f3dffef9654f8145d6bccf468f90ae391@1752424 13f79535-47bb-0310-9956-ffa450edef68
| src/test/java/org/apache/commons/jexl3/ScriptCallableTest.java | JEXL: JEXL-205; check interruption status within loop to detect cancellation | <ide><path>rc/test/java/org/apache/commons/jexl3/ScriptCallableTest.java
<ide> import java.util.concurrent.TimeUnit;
<ide> import java.util.concurrent.TimeoutException;
<ide> import org.apache.commons.jexl3.internal.Script;
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.junit.Assert;
<ide> import org.junit.Test;
<ide> |
|
Java | apache-2.0 | 4ca72163d991eb621b0d9fbd4807a65f93561293 | 0 | fitermay/intellij-community,izonder/intellij-community,joewalnes/idea-community,fnouama/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,apixandru/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,diorcety/intellij-community,petteyg/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,kool79/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,robovm/robovm-studio,fnouama/intellij-community,allotria/intellij-community,hurricup/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,asedunov/intellij-community,kool79/intellij-community,retomerz/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,samthor/intellij-community,hurricup/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,xfournet/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,amith01994/intellij-community,caot/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,consulo/consulo,caot/intellij-community,kdwink/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,jexp/idea2,orekyuu/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,samthor/intellij-community,fnouama/intellij-community,izonder/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,FHannes/intellij-community,kdwink/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,clumsy/intellij-community,xfournet/intellij-community,clumsy/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,supersven/intellij-community,signed/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,kool79/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,diorcety/intellij-community,allotria/intellij-community,kool79/intellij-community,asedunov/intellij-community,apixandru/intellij-community,adedayo/intellij-community,vladmm/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,allotria/intellij-community,vvv1559/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,signed/intellij-community,jexp/idea2,ryano144/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ernestp/consulo,dslomov/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,consulo/consulo,hurricup/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,ibinti/intellij-community,blademainer/intellij-community,allotria/intellij-community,samthor/intellij-community,fitermay/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,youdonghai/intellij-community,samthor/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,ryano144/intellij-community,signed/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,joewalnes/idea-community,asedunov/intellij-community,ryano144/intellij-community,hurricup/intellij-community,ryano144/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,slisson/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,signed/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,fnouama/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,robovm/robovm-studio,jagguli/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,Lekanich/intellij-community,caot/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,jexp/idea2,fitermay/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,adedayo/intellij-community,ryano144/intellij-community,clumsy/intellij-community,ernestp/consulo,signed/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,FHannes/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,ernestp/consulo,akosyakov/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,joewalnes/idea-community,samthor/intellij-community,ahb0327/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,joewalnes/idea-community,jexp/idea2,ivan-fedorov/intellij-community,holmes/intellij-community,apixandru/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,samthor/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,kdwink/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,semonte/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,semonte/intellij-community,fitermay/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,supersven/intellij-community,izonder/intellij-community,signed/intellij-community,apixandru/intellij-community,robovm/robovm-studio,da1z/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,jexp/idea2,Lekanich/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,petteyg/intellij-community,izonder/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,kool79/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,holmes/intellij-community,hurricup/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,consulo/consulo,da1z/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,da1z/intellij-community,supersven/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,petteyg/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,retomerz/intellij-community,FHannes/intellij-community,diorcety/intellij-community,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,vladmm/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,jagguli/intellij-community,amith01994/intellij-community,caot/intellij-community,asedunov/intellij-community,kool79/intellij-community,kdwink/intellij-community,fnouama/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,holmes/intellij-community,dslomov/intellij-community,hurricup/intellij-community,vladmm/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,signed/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,caot/intellij-community,amith01994/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,signed/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,jexp/idea2,MichaelNedzelsky/intellij-community,kool79/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,semonte/intellij-community,tmpgit/intellij-community,slisson/intellij-community,fitermay/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,asedunov/intellij-community,clumsy/intellij-community,FHannes/intellij-community,vladmm/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,izonder/intellij-community,slisson/intellij-community,wreckJ/intellij-community,semonte/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,slisson/intellij-community,ibinti/intellij-community,vladmm/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,signed/intellij-community,apixandru/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,slisson/intellij-community,robovm/robovm-studio,dslomov/intellij-community,semonte/intellij-community,slisson/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,allotria/intellij-community,jexp/idea2,Distrotech/intellij-community,asedunov/intellij-community,ernestp/consulo,ahb0327/intellij-community,petteyg/intellij-community,da1z/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,apixandru/intellij-community,izonder/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,signed/intellij-community,holmes/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,petteyg/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,SerCeMan/intellij-community,jexp/idea2,consulo/consulo,SerCeMan/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,signed/intellij-community,ibinti/intellij-community,supersven/intellij-community,supersven/intellij-community,nicolargo/intellij-community,da1z/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,izonder/intellij-community,ibinti/intellij-community,caot/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,caot/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,clumsy/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,ibinti/intellij-community,xfournet/intellij-community,signed/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,izonder/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ahb0327/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,signed/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,hurricup/intellij-community,retomerz/intellij-community,semonte/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,FHannes/intellij-community,holmes/intellij-community,xfournet/intellij-community,dslomov/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,FHannes/intellij-community,kool79/intellij-community,caot/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,clumsy/intellij-community,izonder/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,caot/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,allotria/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,ibinti/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,fnouama/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,supersven/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,jagguli/intellij-community,kdwink/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,asedunov/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,apixandru/intellij-community,allotria/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,vladmm/intellij-community | /*
* Copyright 2000-2007 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.util.containers;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* @author Dmitry Avdeev
*/
public class MultiMap<K, V> {
private final Map<K, Collection<V>> myMap;
public MultiMap() {
myMap = createMap();
}
protected Map<K, Collection<V>> createMap() {
return new HashMap<K, Collection<V>>();
}
protected Collection<V> createCollection() {
return new ArrayList<V>();
}
protected Collection<V> createEmptyCollection() {
return Collections.emptyList();
}
public void putValue(K key, V value) {
Collection<V> list = myMap.get(key);
if (list == null) {
list = createCollection();
myMap.put(key, list);
}
list.add(value);
}
public boolean isEmpty() {
for(Collection<V> valueList: myMap.values()) {
if (!valueList.isEmpty()) {
return false;
}
}
return true;
}
public boolean containsScalarValue(V value) {
for(Collection<V> valueList: myMap.values()) {
if (valueList.contains(value)) {
return true;
}
}
return false;
}
@NotNull
public Collection<V> get(final K key) {
final Collection<V> collection = myMap.get(key);
return collection == null ? createEmptyCollection() : collection;
}
public Set<K> keySet() {
return myMap.keySet();
}
public int size() {
return myMap.size();
}
public void put(final K key, final Collection<V> values) {
myMap.put(key, values);
}
public void removeValue(final K key, final V value) {
final Collection<V> values = myMap.get(key);
values.remove(value);
if (values.isEmpty()) {
myMap.remove(key);
}
}
public Collection<? extends V> values() {
ArrayList<V> result = new ArrayList<V>();
for (Collection<V> vs : myMap.values()) {
result.addAll(vs);
}
return result;
}
public void clear() {
myMap.clear();
}
public Collection<V> remove(K key) {
return myMap.remove(key);
}
}
| util/src/com/intellij/util/containers/MultiMap.java | /*
* Copyright 2000-2007 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.util.containers;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* @author Dmitry Avdeev
*/
public class MultiMap<K, V> {
private final Map<K, Collection<V>> myMap;
public MultiMap() {
myMap = createMap();
}
protected Map<K, Collection<V>> createMap() {
return new HashMap<K, Collection<V>>();
}
protected Collection<V> createCollection() {
return new ArrayList<V>();
}
protected Collection<V> createEmptyCollection() {
return Collections.emptyList();
}
public void putValue(K key, V value) {
Collection<V> list = myMap.get(key);
if (list == null) {
list = createCollection();
myMap.put(key, list);
}
list.add(value);
}
public boolean isEmpty() {
for(Collection<V> valueList: myMap.values()) {
if (!valueList.isEmpty()) {
return false;
}
}
return true;
}
public boolean containsScalarValue(V value) {
for(Collection<V> valueList: myMap.values()) {
if (valueList.contains(value)) {
return true;
}
}
return false;
}
@NotNull
public Collection<V> get(final K key) {
final Collection<V> collection = myMap.get(key);
return collection == null ? createEmptyCollection() : collection;
}
public Set<K> keySet() {
return myMap.keySet();
}
public int size() {
return myMap.size();
}
public void put(final K key, final Collection<V> values) {
myMap.put(key, values);
}
public void removeValue(final K key, final V value) {
final Collection<V> values = myMap.get(key);
values.remove(value);
if (values.isEmpty()) {
myMap.remove(key);
}
}
public Collection<? extends V> values() {
ArrayList<V> result = new ArrayList<V>();
for (Collection<V> vs : myMap.values()) {
result.addAll(vs);
}
return result;
}
public void clear() {
myMap.clear();
}
}
| MultiMap#remove
| util/src/com/intellij/util/containers/MultiMap.java | MultiMap#remove | <ide><path>til/src/com/intellij/util/containers/MultiMap.java
<ide> public void clear() {
<ide> myMap.clear();
<ide> }
<add>
<add> public Collection<V> remove(K key) {
<add> return myMap.remove(key);
<add> }
<ide> } |
|
JavaScript | isc | 965c4e9d8b63c2e70b3e69782eead28d5534c511 | 0 | francisbrito/node-restful-qs | 'use strict';
var assert = require('assert');
var querystring = require('querystring');
var assign = require('object-assign');
var chain = require('./lib/helpers/chain');
var except = require('./lib/helpers/except');
var isEitherStringOrObject = require('./lib/helpers/is-either-string-or-object');
var DEFAULT_QUERY = {
link: '',
sort: '',
embed: '',
fields: '',
pagination: {
skip: 0,
page: 1,
limit: 0,
},
};
var BLACK_LISTED_QUERY_PARAMETERS = [
'skip',
'link',
'page',
'sort',
'embed',
'limit',
'fields',
'pagination',
];
function parseQuery(qs) {
var rawQuery;
var parsedQuery;
var transformations = [
chain(parseQueryParamAsArray('sort'), parseSortingFrom),
parseQueryParamAsArray('fields'),
parsePaginationFrom,
parseQueryParamAsArray('embed'),
parseQueryParamAsArray('link'),
parseFilterFrom,
];
assert(qs, '`qs` parameter is missing.');
assert(isEitherStringOrObject(qs), '`qs` parameter must be either a string or an object.');
qs = typeof qs === 'string' ? querystring.parse(qs) : qs;
rawQuery = assign({}, DEFAULT_QUERY, qs);
rawQuery.pagination = assign({}, DEFAULT_QUERY.pagination, rawQuery.pagination);
parsedQuery = transformations
.map(function (transform) { return transform(rawQuery); })
.reduce(function (query, field) { return assign({}, query, field); }, {});
return parsedQuery;
}
function parseSortingFrom(q) {
var sort = q.sort.map(
function (sf) {
var sortFieldName = getFieldName(sf);
var sortFieldDirection = getSortDirection(sf);
var sorting = {};
sorting[sortFieldName] = sortFieldDirection;
return sorting;
}
)
.reduce(function (query, f) { return assign({}, query, f); }, {});
return { sort: sort };
}
function getFieldName(sf) {
return sf[0] === '-' ? sf.slice(1) : sf;
}
function getSortDirection(sf) {
return sf[0] === '-' ? 'descending' : 'ascending';
}
function parseQueryParamAsArray(p) {
return function parseQueryParameter(q) {
var query = {};
query[p] = q[p].split(',');
return query;
};
}
function parsePaginationFrom(q) {
var parsedSkip = parseInt(q.skip, 10);
var parsedPage = parseInt(q.page, 10);
var parsedLimit = parseInt(q.limit, 10);
var skip = isNaN(parsedSkip) ? DEFAULT_QUERY.pagination.skip : parsedSkip;
var page = isNaN(parsedPage) ? DEFAULT_QUERY.pagination.page : parsedPage;
var limit = isNaN(parsedLimit) ? DEFAULT_QUERY.pagination.limit : parsedLimit;
return { pagination: { skip: skip, page: page, limit: limit } };
}
function parseFilterFrom(q) {
return except(BLACK_LISTED_QUERY_PARAMETERS, q);
}
module.exports = parseQuery;
| index.js | 'use strict';
var assert = require('assert');
var querystring = require('querystring');
var assign = require('object-assign');
var chain = require('./lib/helpers/chain');
var except = require('./lib/helpers/except');
var isEitherStringOrObject = require('./lib/helpers/is-either-string-or-object');
var DEFAULT_QUERY = {
link: '',
sort: '',
embed: '',
fields: '',
pagination: {
skip: 0,
page: 1,
limit: 0,
},
};
var BLACK_LISTED_QUERY_PARAMETERS = [
'skip',
'link',
'page',
'sort',
'embed',
'limit',
'fields',
'pagination',
];
function parseQuery(qs) {
var rawQuery;
var parsedQuery;
var transformations = [
chain(parseQueryParamAsArray('sort'), transformToSorting),
parseQueryParamAsArray('fields'),
parsePaginationFrom,
parseQueryParamAsArray('embed'),
parseQueryParamAsArray('link'),
parseFilterFrom,
];
assert(qs, '`qs` parameter is missing.');
assert(isEitherStringOrObject(qs), '`qs` parameter must be either a string or an object.');
qs = typeof qs === 'string' ? querystring.parse(qs) : qs;
rawQuery = assign({}, DEFAULT_QUERY, qs);
rawQuery.pagination = assign({}, DEFAULT_QUERY.pagination, rawQuery.pagination);
parsedQuery = transformations
.map(function (transform) { return transform(rawQuery); })
.reduce(function (query, field) { return assign({}, query, field); }, {});
return parsedQuery;
}
function transformToSorting(q) {
var sort = q.sort.map(
function (sf) {
var sortFieldName = getFieldName(sf);
var sortFieldDirection = getSortDirection(sf);
var sorting = {};
sorting[sortFieldName] = sortFieldDirection;
return sorting;
}
)
.reduce(function (query, f) { return assign({}, query, f); }, {});
return { sort: sort };
}
function getFieldName(sf) {
return sf[0] === '-' ? sf.slice(1) : sf;
}
function getSortDirection(sf) {
return sf[0] === '-' ? 'descending' : 'ascending';
}
function parseQueryParamAsArray(p) {
return function parseQueryParameter(q) {
var query = {};
query[p] = q[p].split(',');
return query;
};
}
function parsePaginationFrom(q) {
var parsedSkip = parseInt(q.skip, 10);
var parsedPage = parseInt(q.page, 10);
var parsedLimit = parseInt(q.limit, 10);
var skip = isNaN(parsedSkip) ? DEFAULT_QUERY.pagination.skip : parsedSkip;
var page = isNaN(parsedPage) ? DEFAULT_QUERY.pagination.page : parsedPage;
var limit = isNaN(parsedLimit) ? DEFAULT_QUERY.pagination.limit : parsedLimit;
return { pagination: { skip: skip, page: page, limit: limit } };
}
function parseFilterFrom(q) {
return except(BLACK_LISTED_QUERY_PARAMETERS, q);
}
module.exports = parseQuery;
| Rename parse `sort` query parameter function.
| index.js | Rename parse `sort` query parameter function. | <ide><path>ndex.js
<ide> var rawQuery;
<ide> var parsedQuery;
<ide> var transformations = [
<del> chain(parseQueryParamAsArray('sort'), transformToSorting),
<add> chain(parseQueryParamAsArray('sort'), parseSortingFrom),
<ide> parseQueryParamAsArray('fields'),
<ide> parsePaginationFrom,
<ide> parseQueryParamAsArray('embed'),
<ide> return parsedQuery;
<ide> }
<ide>
<del>function transformToSorting(q) {
<add>function parseSortingFrom(q) {
<ide> var sort = q.sort.map(
<ide> function (sf) {
<ide> var sortFieldName = getFieldName(sf); |
|
Java | apache-2.0 | 04a6bf507bc323ae069e15813c1b71a90b7145f4 | 0 | p6spy/p6spy,p6spy/p6spy | /**
* P6Spy
*
* Copyright (C) 2002 - 2019 P6Spy
*
* 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.p6spy.engine.spy.option;
import com.p6spy.engine.common.P6Util;
import com.p6spy.engine.spy.P6ModuleManager;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Properties;
public class SpyDotProperties implements P6OptionsSource {
public static final String OPTIONS_FILE_PROPERTY = "spy.properties";
public static final String OPTIONS_FILE_CHARSET_PROPERTY = OPTIONS_FILE_PROPERTY.concat(".charset");
public static final String DEFAULT_OPTIONS_FILE = OPTIONS_FILE_PROPERTY;
private final long lastModified;
private SpyDotPropertiesReloader reloader;
private final Map<String, String> options;
/**
* Creates a new instance and loads the properties file if found.
*
* @throws IOException
*/
public SpyDotProperties() throws IOException {
URL url = locate();
if (null == url) {
// no config file preset => skip props loading
lastModified = -1;
options = null;
return;
}
lastModified = lastModified();
InputStream in = null;
try {
in = url.openStream();
final Properties properties = new Properties();
String charsetName = System.getProperty(OPTIONS_FILE_CHARSET_PROPERTY, Charset.defaultCharset().name());
properties.load(new InputStreamReader(in, charsetName));
options = P6Util.getPropertiesMap(properties);
} finally {
if (null != in) {
try {
in.close();
} catch( Exception e ) {
}
}
}
}
/**
* Determines if the file has been modified since it was loaded
*
* @return true if modified, false otherwise
*/
public boolean isModified() {
return lastModified() != lastModified;
}
private long lastModified() {
long lastMod = -1;
URLConnection con = null;
URL url = locate();
if( url != null ) {
try {
con = url.openConnection();
lastMod = con.getLastModified();
} catch (IOException e) {
// ignore
} finally {
if( con != null ) {
// getLastModified opens an input stream if it is a file
// the inputStream must be closed manually!
InputStream in = null;
try {
in = con.getInputStream();
} catch (IOException e) {
}
if( in != null ) {
try {
in.close();
} catch (IOException e) {}
}
}
}
}
return lastMod;
}
private URL locate() {
String propsFileName = System.getProperty(OPTIONS_FILE_PROPERTY, DEFAULT_OPTIONS_FILE);
if (null == propsFileName || propsFileName.isEmpty()) {
propsFileName = DEFAULT_OPTIONS_FILE;
}
return P6Util.locateFile(propsFileName);
}
@Override
public Map<String, String> getOptions() {
return options;
}
@Override
public void preDestroy(P6ModuleManager p6moduleManager) {
if (reloader != null) {
reloader.kill(p6moduleManager);
}
}
@Override
public void postInit(P6ModuleManager p6moduleManager) {
reloader = new SpyDotPropertiesReloader(this, p6moduleManager);
}
}
| src/main/java/com/p6spy/engine/spy/option/SpyDotProperties.java | /**
* P6Spy
*
* Copyright (C) 2002 - 2019 P6Spy
*
* 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.p6spy.engine.spy.option;
import com.p6spy.engine.common.P6Util;
import com.p6spy.engine.spy.P6ModuleManager;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Properties;
public class SpyDotProperties implements P6OptionsSource {
public static final String OPTIONS_FILE_PROPERTY = "spy.properties";
public static final String DEFAULT_OPTIONS_FILE = OPTIONS_FILE_PROPERTY;
private final long lastModified;
private SpyDotPropertiesReloader reloader;
private final Map<String, String> options;
/**
* Creates a new instance and loads the properties file if found.
*
* @throws IOException
*/
public SpyDotProperties() throws IOException {
URL url = locate();
if (null == url) {
// no config file preset => skip props loading
lastModified = -1;
options = null;
return;
}
lastModified = lastModified();
InputStream in = null;
try {
in = url.openStream();
final Properties properties = new Properties();
properties.load(in);
options = P6Util.getPropertiesMap(properties);
} finally {
if (null != in) {
try {
in.close();
} catch( Exception e ) {
}
}
}
}
/**
* Determines if the file has been modified since it was loaded
*
* @return true if modified, false otherwise
*/
public boolean isModified() {
return lastModified() != lastModified;
}
private long lastModified() {
long lastMod = -1;
URLConnection con = null;
URL url = locate();
if( url != null ) {
try {
con = url.openConnection();
lastMod = con.getLastModified();
} catch (IOException e) {
// ignore
} finally {
if( con != null ) {
// getLastModified opens an input stream if it is a file
// the inputStream must be closed manually!
InputStream in = null;
try {
in = con.getInputStream();
} catch (IOException e) {
}
if( in != null ) {
try {
in.close();
} catch (IOException e) {}
}
}
}
}
return lastMod;
}
private URL locate() {
String propsFileName = System.getProperty(OPTIONS_FILE_PROPERTY, DEFAULT_OPTIONS_FILE);
if (null == propsFileName || propsFileName.isEmpty()) {
propsFileName = DEFAULT_OPTIONS_FILE;
}
return P6Util.locateFile(propsFileName);
}
@Override
public Map<String, String> getOptions() {
return options;
}
@Override
public void preDestroy(P6ModuleManager p6moduleManager) {
if (reloader != null) {
reloader.kill(p6moduleManager);
}
}
@Override
public void postInit(P6ModuleManager p6moduleManager) {
reloader = new SpyDotPropertiesReloader(this, p6moduleManager);
}
}
| The file.encoding configuration encoding is used by default to read the configuration file, and the encoding is specified through -Dspy.properties.charset (#492)
| src/main/java/com/p6spy/engine/spy/option/SpyDotProperties.java | The file.encoding configuration encoding is used by default to read the configuration file, and the encoding is specified through -Dspy.properties.charset (#492) | <ide><path>rc/main/java/com/p6spy/engine/spy/option/SpyDotProperties.java
<ide>
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<add>import java.io.InputStreamReader;
<ide> import java.net.URL;
<ide> import java.net.URLConnection;
<add>import java.nio.charset.Charset;
<ide> import java.util.Map;
<ide> import java.util.Properties;
<ide>
<ide> public class SpyDotProperties implements P6OptionsSource {
<ide>
<ide> public static final String OPTIONS_FILE_PROPERTY = "spy.properties";
<add> public static final String OPTIONS_FILE_CHARSET_PROPERTY = OPTIONS_FILE_PROPERTY.concat(".charset");
<ide> public static final String DEFAULT_OPTIONS_FILE = OPTIONS_FILE_PROPERTY;
<ide>
<ide> private final long lastModified;
<del>
<add>
<ide> private SpyDotPropertiesReloader reloader;
<ide>
<ide> private final Map<String, String> options;
<ide>
<ide> /**
<ide> * Creates a new instance and loads the properties file if found.
<del> *
<add> *
<ide> * @throws IOException
<ide> */
<ide> public SpyDotProperties() throws IOException {
<ide> URL url = locate();
<del>
<add>
<ide> if (null == url) {
<ide> // no config file preset => skip props loading
<ide> lastModified = -1;
<ide> options = null;
<ide> return;
<ide> }
<del>
<add>
<ide> lastModified = lastModified();
<ide>
<ide> InputStream in = null;
<ide> try {
<ide> in = url.openStream();
<ide> final Properties properties = new Properties();
<del> properties.load(in);
<add>
<add> String charsetName = System.getProperty(OPTIONS_FILE_CHARSET_PROPERTY, Charset.defaultCharset().name());
<add> properties.load(new InputStreamReader(in, charsetName));
<ide> options = P6Util.getPropertiesMap(properties);
<ide> } finally {
<ide> if (null != in) {
<ide>
<ide> /**
<ide> * Determines if the file has been modified since it was loaded
<del> *
<add> *
<ide> * @return true if modified, false otherwise
<ide> */
<ide> public boolean isModified() {
<ide> return lastModified() != lastModified;
<ide> }
<del>
<add>
<ide> private long lastModified() {
<ide> long lastMod = -1;
<ide> URLConnection con = null;
<ide> URL url = locate();
<ide> if( url != null ) {
<ide> try {
<del> con = url.openConnection();
<add> con = url.openConnection();
<ide> lastMod = con.getLastModified();
<ide> } catch (IOException e) {
<ide> // ignore |
|
Java | apache-2.0 | bca3e8f775a14f6e38de7b51655902d728e8f514 | 0 | onepip/weixin-mp-java | /**
*
*/
package org.hamster.weixinmp.util;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.hamster.weixinmp.dao.entity.base.WxBaseEntity;
import org.hamster.weixinmp.exception.WxException;
import org.hamster.weixinmp.model.WxRespCode;
import org.springframework.http.HttpMethod;
import com.google.gson.Gson;
/**
* @author [email protected]
* @version Jul 28, 2013
*
*/
public class WxUtil {
private WxUtil() {
}
public static final Long currentTimeInSec() {
return Long.valueOf(new Date().getTime() / 1000);
}
@SuppressWarnings("unchecked")
public static final <T> T sendRequest(String url, HttpMethod method,
Map<String, String> params, HttpEntity requestEntity,
Class<T> resultClass) throws WxException {
HttpClient client = HttpClientBuilder.create().build();
HttpRequestBase request = null;
try {
if (HttpMethod.GET.equals(method)) {
request = new HttpGet();
} else if (HttpMethod.POST.equals(method)) {
request = new HttpPost();
if (requestEntity != null) {
((HttpPost) request).setEntity(requestEntity);
}
}
URIBuilder builder = new URIBuilder(url);
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.addParameter(entry.getKey(), entry.getValue());
}
}
request.setURI(builder.build());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String respBody = EntityUtils.toString(entity, "UTF-8");
if (entity != null) {
EntityUtils.consume(entity);
}
if (String.class.isAssignableFrom(resultClass)) {
return (T) respBody;
} else {
Gson gson = new Gson();
if (respBody.indexOf("{\"errcode\"") == 0
|| respBody.indexOf("{\"errmsg\"") == 0) {
WxRespCode exJson = gson.fromJson(respBody,
WxRespCode.class);
if (WxRespCode.class.getName().equals(
resultClass.getName())
&& exJson.getErrcode() == 0) {
return (T) exJson;
} else {
throw new WxException(exJson);
}
}
T result = gson.fromJson(respBody, resultClass);
if (result instanceof WxBaseEntity) {
((WxBaseEntity) result).setCreatedDate(new Date());
}
return result;
}
} catch (IOException e) {
throw new WxException(e);
} catch (URISyntaxException e) {
throw new WxException(e);
}
}
public static StringEntity toJsonStringEntity(Object obj) {
Gson gson = new Gson();
return new StringEntity(gson.toJson(obj), Consts.UTF_8);
}
public static Map<String, String> getAccessTokenParams(String accessToken) {
Map<String, String> result = new HashMap<String, String>();
result.put("access_token", accessToken);
return result;
}
public static String getParameterizedUrl(String url, String... args) {
String result = url;
for (int i = 0; i < args.length; i += 2) {
String p = args[i];
String v = args[i + 1];
result = result.replaceAll(p, v);
}
return result;
}
}
| src/main/java/org/hamster/weixinmp/util/WxUtil.java | /**
*
*/
package org.hamster.weixinmp.util;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.hamster.weixinmp.dao.entity.base.WxBaseEntity;
import org.hamster.weixinmp.exception.WxException;
import org.hamster.weixinmp.model.WxRespCode;
import org.springframework.http.HttpMethod;
import com.google.gson.Gson;
/**
* @author [email protected]
* @version Jul 28, 2013
*
*/
public class WxUtil {
private WxUtil() {
}
public static final Long currentTimeInSec() {
return Long.valueOf(new Date().getTime() / 1000);
}
@SuppressWarnings("unchecked")
public static final <T> T sendRequest(String url, HttpMethod method,
Map<String, String> params, HttpEntity requestEntity,
Class<T> resultClass) throws WxException {
HttpClient client = HttpClientBuilder.create().build();
HttpRequestBase request = null;
try {
if (HttpMethod.GET.equals(method)) {
request = new HttpGet();
} else if (HttpMethod.POST.equals(method)) {
request = new HttpPost();
if (requestEntity != null) {
((HttpPost) request).setEntity(requestEntity);
}
}
URIBuilder builder = new URIBuilder(url);
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.addParameter(entry.getKey(), entry.getValue());
}
}
request.setURI(builder.build());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String respBody = EntityUtils.toString(entity);
if (entity != null) {
EntityUtils.consume(entity);
}
if (String.class.isAssignableFrom(resultClass)) {
return (T) respBody;
} else {
Gson gson = new Gson();
if (respBody.indexOf("{\"errcode\"") == 0
|| respBody.indexOf("{\"errmsg\"") == 0) {
WxRespCode exJson = gson.fromJson(respBody,
WxRespCode.class);
if (WxRespCode.class.getName().equals(
resultClass.getName())
&& exJson.getErrcode() == 0) {
return (T) exJson;
} else {
throw new WxException(exJson);
}
}
T result = gson.fromJson(respBody, resultClass);
if (result instanceof WxBaseEntity) {
((WxBaseEntity) result).setCreatedDate(new Date());
}
return result;
}
} catch (IOException e) {
throw new WxException(e);
} catch (URISyntaxException e) {
throw new WxException(e);
}
}
public static StringEntity toJsonStringEntity(Object obj) {
Gson gson = new Gson();
return new StringEntity(gson.toJson(obj), Consts.UTF_8);
}
public static Map<String, String> getAccessTokenParams(String accessToken) {
Map<String, String> result = new HashMap<String, String>();
result.put("access_token", accessToken);
return result;
}
public static String getParameterizedUrl(String url, String... args) {
String result = url;
for (int i = 0; i < args.length; i += 2) {
String p = args[i];
String v = args[i + 1];
result = result.replaceAll(p, v);
}
return result;
}
}
| utf-8 when getting userinfo | src/main/java/org/hamster/weixinmp/util/WxUtil.java | utf-8 when getting userinfo | <ide><path>rc/main/java/org/hamster/weixinmp/util/WxUtil.java
<ide>
<ide> HttpResponse response = client.execute(request);
<ide> HttpEntity entity = response.getEntity();
<del> String respBody = EntityUtils.toString(entity);
<add> String respBody = EntityUtils.toString(entity, "UTF-8");
<ide> if (entity != null) {
<ide> EntityUtils.consume(entity);
<ide> } |
|
Java | apache-2.0 | f7ac518041bcd407190667826bb717b2c3f8f596 | 0 | orangesignal/orangesignal-csv,blqthien/orangesignal-csv,Koichi-Kobayashi/orangesignal-csv | /**
* Copyright (C) 2001-2002 Michel Ishizuka All rights reserved.
*
* 以下の条件に同意するならばソースとバイナリ形式の再配布と使用を
* 変更の有無にかかわらず許可する。
*
* 1.ソースコードの再配布において著作権表示と この条件のリスト
* および下記の声明文を保持しなくてはならない。
*
* 2.バイナリ形式の再配布において著作権表示と この条件のリスト
* および下記の声明文を使用説明書もしくは その他の配布物内に
* 含む資料に記述しなければならない。
*
* このソフトウェアは石塚美珠瑠によって無保証で提供され、特定の目
* 的を達成できるという保証、商品価値が有るという保証にとどまらず、
* いかなる明示的および暗示的な保証もしない。
* 石塚美珠瑠は このソフトウェアの使用による直接的、間接的、偶発
* 的、特殊な、典型的な、あるいは必然的な損害(使用によるデータの
* 損失、業務の中断や見込まれていた利益の遺失、代替製品もしくは
* サービスの導入費等が考えられるが、決してそれだけに限定されない
* 損害)に対して、いかなる事態の原因となったとしても、契約上の責
* 任や無過失責任を含む いかなる責任があろうとも、たとえそれが不
* 正行為のためであったとしても、またはそのような損害の可能性が報
* 告されていたとしても一切の責任を負わないものとする。
*/
package jp.gr.java_conf.dangan.util.lha;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Properties;
/**
* LHAの各種定数を定義する。
*
* <pre>
* -- revision history --
* $Log: CompressMethod.java,v $
* Revision 1.1 2002/12/08 00:00:00 dangan
* [change]
* クラス名を LhaConstants から CompressMethod へと変更。
*
* Revision 1.0 2002/07/24 00:00:00 dangan
* add to version control
* [change]
* LhaUtil の connectExtractInputStream を connectDecoder として
* connectCompressOutputStream を connectEncoder として引き継ぐ。
* LhaUtil の CompressMethodTo????????? を引き継ぐ。
* [maintanance]
* ソース整備
* タブ廃止
* ライセンス文の修正
*
* </pre>
*
* @author $Author: dangan $
* @version $Revision: 1.1 $
*/
final class CompressMethod {
/**
* 圧縮形式を示す文字列。 LH0 は 無圧縮を示す "-lh0-" である。
*/
public static final String LH0 = "-lh0-";
/**
* 圧縮形式を示す文字列。 LH1 は前段に 4キロバイトの辞書、最大一致長60バイトの LZSS法、後段に 適応的ハフマン法を使用することを意味する "-lh1-" である。
*/
public static final String LH1 = "-lh1-";
/**
* 圧縮形式を示す文字列。 LH2 は前段に 8キロバイトの辞書、最大一致長256バイトの LZSS法、後段に 適応的ハフマン法を使用することを意味する "-lh2-" である。 この圧縮法は LH1 から LH5 への改良途中で試験的に 使われたが、現在は使用されていない。
*/
public static final String LH2 = "-lh2-";
/**
* 圧縮形式を示す文字列。 LH3 は前段に 8キロバイトの辞書、最大一致長256バイトの LZSS法、後段に 静的ハフマン法を使用することを意味する "-lh3-" である。 この圧縮法は LH1 から LH5 への改良途中で試験的に 使われたが、現在は使用されていない。
*/
public static final String LH3 = "-lh3-";
/**
* 圧縮形式を示す文字列。 LH4 は前段に 4キロバイトの辞書、最大一致長256バイトの LZSS法、後段に 静的ハフマン法を使用することを意味する "-lh4-" である。 この圧縮法は 1990年代前半の非力なマシン上で圧縮を行う際、 LH5圧縮を行うだけのシステム資源を得られなかった時に使わ れたが、現在は殆ど使用されていない。
*/
public static final String LH4 = "-lh4-";
/**
* 圧縮形式を示す文字列。 LH5 は前段に 8キロバイトの辞書、最大一致長256バイトの LZSS法、後段に 静的ハフマン法を使用することを意味する "-lh5-" である。 現在、LHAで標準で使用される圧縮法である。
*/
public static final String LH5 = "-lh5-";
/**
* 圧縮形式を示す文字列。 LH6 は前段に 32キロバイトの辞書、最大一致長256バイトの LZSS法、後段に 静的ハフマン法を使用することを意味する "-lh6-" である。 "-lh6-" という文字列は LH7 の圧縮法の実験に使用されて いた。そのため、LHAの実験版が作成した書庫には "-lh6-" の文字列を使用しながら LH7 形式で圧縮されているものが 存在するらしい。 また この圧縮法は開発されてから 10年近く経つが未だに 公の場所に この圧縮法で圧縮された書庫は登録しないこと が望ましいとされている。
*/
public static final String LH6 = "-lh6-";
/**
* 圧縮形式を示す文字列。 LH7 は前段に 64キロバイトの辞書、最大一致長256バイトの LZSS法、後段に 静的ハフマン法を使用することを意味する "-lh7-" である。 また この圧縮法は開発されてから 10年近く経つが未だに 公の場所に この圧縮法で圧縮された書庫は登録しないこと が望ましいとされている。
*/
public static final String LH7 = "-lh7-";
/**
* 圧縮形式を示す文字列。 LHD は無圧縮で、ディレクトリを格納していることを示す "-lhd-" である。
*/
public static final String LHD = "-lhd-";
/**
* 圧縮形式を示す文字列。 LZS は 2キロバイトの辞書、最大一致長17バイトの LZSS法を使用することを示す "-lzs-" である。 "-lzs-" は LHAが作成される前にメジャーであった Larc の形式であり、当時の互換性に配慮して定義さ れた。現在は殆ど使用されていない。
*/
public static final String LZS = "-lzs-";
/**
* 圧縮形式を示す文字列。 LZ4 は 無圧縮を示す "-lz4-" である。 "-lz4-" は LHAが作成される前にメジャーであった Larc の形式であり、当時の互換性に配慮して定義さ れた。現在は殆ど使用されていない。
*/
public static final String LZ4 = "-lz4-";
/**
* 圧縮形式を示す文字列。 LZ5 は 4キロバイトの辞書、最大一致長17バイトの LZSS法を使用することを示す "-lz5-" である。 "-lz5-" は LHAが作成される前にメジャーであった Larc の形式であり、当時の互換性に配慮して定義さ れた。現在は殆ど使用されていない。
*/
public static final String LZ5 = "-lz5-";
/**
* デフォルトコンストラクタ使用不可
*/
private CompressMethod() {}
// ------------------------------------------------------------------
// convert to LZSS parameter
/**
* 圧縮法識別子から 辞書サイズを得る。
*
* @param method 圧縮法識別子
* @return 辞書サイズ
*/
public static int toDictionarySize(final String method) {
if (LZS.equalsIgnoreCase(method)) {
return 2048;
} else if (LZ5.equalsIgnoreCase(method)) {
return 4096;
} else if (LH1.equalsIgnoreCase(method)) {
return 4096;
} else if (LH2.equalsIgnoreCase(method)) {
return 8192;
} else if (LH3.equalsIgnoreCase(method)) {
return 8192;
} else if (LH4.equalsIgnoreCase(method)) {
return 4096;
} else if (LH5.equalsIgnoreCase(method)) {
return 8192;
} else if (LH6.equalsIgnoreCase(method)) {
return 32768;
} else if (LH7.equalsIgnoreCase(method)) {
return 65536;
} else if (LZ4.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (LH0.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (LHD.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (method == null) {
throw new NullPointerException("method");
} else {
throw new IllegalArgumentException("Unknown compress method. " + method);
}
}
/**
* 圧縮法識別子から 圧縮/非圧縮の閾値を得る。
*
* @param method 圧縮法識別子
* @return 圧縮/非圧縮
*/
public static int toThreshold(final String method) {
if (LZS.equalsIgnoreCase(method)) {
return 2;
} else if (LZ5.equalsIgnoreCase(method)) {
return 3;
} else if (LH1.equalsIgnoreCase(method)) {
return 3;
} else if (LH2.equalsIgnoreCase(method)) {
return 3;
} else if (LH3.equalsIgnoreCase(method)) {
return 3;
} else if (LH4.equalsIgnoreCase(method)) {
return 3;
} else if (LH5.equalsIgnoreCase(method)) {
return 3;
} else if (LH6.equalsIgnoreCase(method)) {
return 3;
} else if (LH7.equalsIgnoreCase(method)) {
return 3;
} else if (LZ4.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (LH0.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (LHD.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (method == null) {
throw new NullPointerException("method");
} else {
throw new IllegalArgumentException("Unknown compress method. " + method);
}
}
/**
* 圧縮法識別子から 最大一致長を得る。
*
* @param method 圧縮法識別子
* @return 最大一致長
*/
public static int toMaxMatch(final String method) {
if (LZS.equalsIgnoreCase(method)) {
return 17;
} else if (LZ5.equalsIgnoreCase(method)) {
return 18;
} else if (LH1.equalsIgnoreCase(method)) {
return 60;
} else if (LH2.equalsIgnoreCase(method)) {
return 256;
} else if (LH3.equalsIgnoreCase(method)) {
return 256;
} else if (LH4.equalsIgnoreCase(method)) {
return 256;
} else if (LH5.equalsIgnoreCase(method)) {
return 256;
} else if (LH6.equalsIgnoreCase(method)) {
return 256;
} else if (LH7.equalsIgnoreCase(method)) {
return 256;
} else if (LZ4.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (LH0.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (LHD.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (method == null) {
throw new NullPointerException("method");
} else {
throw new IllegalArgumentException("Unknown compress method. " + method);
}
}
// ------------------------------------------------------------------
// shared method
/**
* property に設定された生成式を利用して method の圧縮法でデータを圧縮し、outに出力するストリームを構築する。
*
* @param out 圧縮データ出力先のストリーム
* @param method 圧縮法識別子
* @param property 各圧縮形式に対応した符号器の生成式等が含まれるプロパティ
* @return method の圧縮法でデータを圧縮し、outに出力するストリーム
*/
public static OutputStream connectEncoder(final OutputStream out, final String method, final Properties property) {
final String key = "lha." + getCore(method) + ".encoder";
String generator = property.getProperty(key);
if (generator == null) {
generator = LhaProperty.getProperty(key);
}
String packages = property.getProperty("lha.packages");
if (packages == null) {
packages = LhaProperty.getProperty("lha.packages");
}
final Hashtable<String, Object> substitute = new Hashtable<String, Object>();
substitute.put("out", out);
return (OutputStream) LhaProperty.parse(generator, substitute, packages);
}
/**
* property に設定された生成式を利用して in から method の圧縮法で圧縮されたデータを解凍し 供給する入力ストリームを構築する。
*
* @param in 圧縮データを供給するストリーム
* @param method 圧縮法識別子
* @param property 各圧縮形式に対応した復号器の生成式等が含まれるプロパティ
* @return in から method の圧縮法で圧縮されたデータを解凍し 供給する入力ストリームを構築する。
*/
public static InputStream connectDecoder(final InputStream in, final String method, final Properties property, final long length) {
final String key = "lha." + getCore(method) + ".decoder";
String generator = property.getProperty(key);
if (generator == null) {
generator = LhaProperty.getProperty(key);
}
String packages = property.getProperty("lha.packages");
if (packages == null) {
packages = LhaProperty.getProperty("lha.packages");
}
final Hashtable<String, Object> substitute = new Hashtable<String, Object>();
substitute.put("in", in);
substitute.put("length", new Long(length));
return (InputStream) LhaProperty.parse(generator, substitute, packages);
}
// ------------------------------------------------------------------
// local method
/**
* 圧縮法識別子 の前後の '-' を取り去って LhaProperty のキー lha.???.encoder / lha.???.decoder の ??? に入る文字列を生成する。
*
* @param method 圧縮法識別子
* @return キーの中心に使える文字列
*/
private static String getCore(final String method) {
if (method.startsWith("-") && method.endsWith("-")) {
return method.substring(1, method.lastIndexOf('-')).toLowerCase();
}
throw new IllegalArgumentException("");
}
} | src/main/java/jp/gr/java_conf/dangan/util/lha/CompressMethod.java | /**
* Copyright (C) 2001-2002 Michel Ishizuka All rights reserved.
*
* 以下の条件に同意するならばソースとバイナリ形式の再配布と使用を
* 変更の有無にかかわらず許可する。
*
* 1.ソースコードの再配布において著作権表示と この条件のリスト
* および下記の声明文を保持しなくてはならない。
*
* 2.バイナリ形式の再配布において著作権表示と この条件のリスト
* および下記の声明文を使用説明書もしくは その他の配布物内に
* 含む資料に記述しなければならない。
*
* このソフトウェアは石塚美珠瑠によって無保証で提供され、特定の目
* 的を達成できるという保証、商品価値が有るという保証にとどまらず、
* いかなる明示的および暗示的な保証もしない。
* 石塚美珠瑠は このソフトウェアの使用による直接的、間接的、偶発
* 的、特殊な、典型的な、あるいは必然的な損害(使用によるデータの
* 損失、業務の中断や見込まれていた利益の遺失、代替製品もしくは
* サービスの導入費等が考えられるが、決してそれだけに限定されない
* 損害)に対して、いかなる事態の原因となったとしても、契約上の責
* 任や無過失責任を含む いかなる責任があろうとも、たとえそれが不
* 正行為のためであったとしても、またはそのような損害の可能性が報
* 告されていたとしても一切の責任を負わないものとする。
*/
package jp.gr.java_conf.dangan.util.lha;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Properties;
/**
* LHAの各種定数を定義する。
*
* <pre>
* -- revision history --
* $Log: CompressMethod.java,v $
* Revision 1.1 2002/12/08 00:00:00 dangan
* [change]
* クラス名を LhaConstants から CompressMethod へと変更。
*
* Revision 1.0 2002/07/24 00:00:00 dangan
* add to version control
* [change]
* LhaUtil の connectExtractInputStream を connectDecoder として
* connectCompressOutputStream を connectEncoder として引き継ぐ。
* LhaUtil の CompressMethodTo????????? を引き継ぐ。
* [maintanance]
* ソース整備
* タブ廃止
* ライセンス文の修正
*
* </pre>
*
* @author $Author: dangan $
* @version $Revision: 1.1 $
*/
final class CompressMethod {
/**
* 圧縮形式を示す文字列。 LH0 は 無圧縮を示す "-lh0-" である。
*/
public static final String LH0 = "-lh0-";
/**
* 圧縮形式を示す文字列。 LH1 は前段に 4キロバイトの辞書、最大一致長60バイトの LZSS法、後段に 適応的ハフマン法を使用することを意味する "-lh1-" である。
*/
public static final String LH1 = "-lh1-";
/**
* 圧縮形式を示す文字列。 LH2 は前段に 8キロバイトの辞書、最大一致長256バイトの LZSS法、後段に 適応的ハフマン法を使用することを意味する "-lh2-" である。 この圧縮法は LH1 から LH5 への改良途中で試験的に 使われたが、現在は使用されていない。
*/
public static final String LH2 = "-lh2-";
/**
* 圧縮形式を示す文字列。 LH3 は前段に 8キロバイトの辞書、最大一致長256バイトの LZSS法、後段に 静的ハフマン法を使用することを意味する "-lh3-" である。 この圧縮法は LH1 から LH5 への改良途中で試験的に 使われたが、現在は使用されていない。
*/
public static final String LH3 = "-lh3-";
/**
* 圧縮形式を示す文字列。 LH4 は前段に 4キロバイトの辞書、最大一致長256バイトの LZSS法、後段に 静的ハフマン法を使用することを意味する "-lh4-" である。 この圧縮法は 1990年代前半の非力なマシン上で圧縮を行う際、 LH5圧縮を行うだけのシステム資源を得られなかった時に使わ れたが、現在は殆ど使用されていない。
*/
public static final String LH4 = "-lh4-";
/**
* 圧縮形式を示す文字列。 LH5 は前段に 8キロバイトの辞書、最大一致長256バイトの LZSS法、後段に 静的ハフマン法を使用することを意味する "-lh5-" である。 現在、LHAで標準で使用される圧縮法である。
*/
public static final String LH5 = "-lh5-";
/**
* 圧縮形式を示す文字列。 LH6 は前段に 32キロバイトの辞書、最大一致長256バイトの LZSS法、後段に 静的ハフマン法を使用することを意味する "-lh6-" である。 "-lh6-" という文字列は LH7 の圧縮法の実験に使用されて いた。そのため、LHAの実験版が作成した書庫には "-lh6-" の文字列を使用しながら LH7 形式で圧縮されているものが 存在するらしい。 また この圧縮法は開発されてから 10年近く経つが未だに 公の場所に この圧縮法で圧縮された書庫は登録しないこと が望ましいとされている。
*/
public static final String LH6 = "-lh6-";
/**
* 圧縮形式を示す文字列。 LH7 は前段に 64キロバイトの辞書、最大一致長256バイトの LZSS法、後段に 静的ハフマン法を使用することを意味する "-lh7-" である。 また この圧縮法は開発されてから 10年近く経つが未だに 公の場所に この圧縮法で圧縮された書庫は登録しないこと が望ましいとされている。
*/
public static final String LH7 = "-lh7-";
/**
* 圧縮形式を示す文字列。 LHD は無圧縮で、ディレクトリを格納していることを示す "-lhd-" である。
*/
public static final String LHD = "-lhd-";
/**
* 圧縮形式を示す文字列。 LZS は 2キロバイトの辞書、最大一致長17バイトの LZSS法を使用することを示す "-lzs-" である。 "-lzs-" は LHAが作成される前にメジャーであった Larc の形式であり、当時の互換性に配慮して定義さ れた。現在は殆ど使用されていない。
*/
public static final String LZS = "-lzs-";
/**
* 圧縮形式を示す文字列。 LZ4 は 無圧縮を示す "-lz4-" である。 "-lz4-" は LHAが作成される前にメジャーであった Larc の形式であり、当時の互換性に配慮して定義さ れた。現在は殆ど使用されていない。
*/
public static final String LZ4 = "-lz4-";
/**
* 圧縮形式を示す文字列。 LZ5 は 4キロバイトの辞書、最大一致長17バイトの LZSS法を使用することを示す "-lz5-" である。 "-lz5-" は LHAが作成される前にメジャーであった Larc の形式であり、当時の互換性に配慮して定義さ れた。現在は殆ど使用されていない。
*/
public static final String LZ5 = "-lz5-";
/**
* デフォルトコンストラクタ使用不可
*/
private CompressMethod() {}
// ------------------------------------------------------------------
// convert to LZSS parameter
/**
* 圧縮法識別子から 辞書サイズを得る。
*
* @param method 圧縮法識別子
* @return 辞書サイズ
*/
public static int toDictionarySize(final String method) {
if (CompressMethod.LZS.equalsIgnoreCase(method)) {
return 2048;
} else if (CompressMethod.LZ5.equalsIgnoreCase(method)) {
return 4096;
} else if (CompressMethod.LH1.equalsIgnoreCase(method)) {
return 4096;
} else if (CompressMethod.LH2.equalsIgnoreCase(method)) {
return 8192;
} else if (CompressMethod.LH3.equalsIgnoreCase(method)) {
return 8192;
} else if (CompressMethod.LH4.equalsIgnoreCase(method)) {
return 4096;
} else if (CompressMethod.LH5.equalsIgnoreCase(method)) {
return 8192;
} else if (CompressMethod.LH6.equalsIgnoreCase(method)) {
return 32768;
} else if (CompressMethod.LH7.equalsIgnoreCase(method)) {
return 65536;
} else if (CompressMethod.LZ4.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (CompressMethod.LH0.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (CompressMethod.LHD.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (method == null) {
throw new NullPointerException("method");
} else {
throw new IllegalArgumentException("Unknown compress method. " + method);
}
}
/**
* 圧縮法識別子から 圧縮/非圧縮の閾値を得る。
*
* @param method 圧縮法識別子
* @return 圧縮/非圧縮
*/
public static int toThreshold(final String method) {
if (CompressMethod.LZS.equalsIgnoreCase(method)) {
return 2;
} else if (CompressMethod.LZ5.equalsIgnoreCase(method)) {
return 3;
} else if (CompressMethod.LH1.equalsIgnoreCase(method)) {
return 3;
} else if (CompressMethod.LH2.equalsIgnoreCase(method)) {
return 3;
} else if (CompressMethod.LH3.equalsIgnoreCase(method)) {
return 3;
} else if (CompressMethod.LH4.equalsIgnoreCase(method)) {
return 3;
} else if (CompressMethod.LH5.equalsIgnoreCase(method)) {
return 3;
} else if (CompressMethod.LH6.equalsIgnoreCase(method)) {
return 3;
} else if (CompressMethod.LH7.equalsIgnoreCase(method)) {
return 3;
} else if (CompressMethod.LZ4.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (CompressMethod.LH0.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (CompressMethod.LHD.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (method == null) {
throw new NullPointerException("method");
} else {
throw new IllegalArgumentException("Unknown compress method. " + method);
}
}
/**
* 圧縮法識別子から 最大一致長を得る。
*
* @param method 圧縮法識別子
* @return 最大一致長
*/
public static int toMaxMatch(final String method) {
if (CompressMethod.LZS.equalsIgnoreCase(method)) {
return 17;
} else if (CompressMethod.LZ5.equalsIgnoreCase(method)) {
return 18;
} else if (CompressMethod.LH1.equalsIgnoreCase(method)) {
return 60;
} else if (CompressMethod.LH2.equalsIgnoreCase(method)) {
return 256;
} else if (CompressMethod.LH3.equalsIgnoreCase(method)) {
return 256;
} else if (CompressMethod.LH4.equalsIgnoreCase(method)) {
return 256;
} else if (CompressMethod.LH5.equalsIgnoreCase(method)) {
return 256;
} else if (CompressMethod.LH6.equalsIgnoreCase(method)) {
return 256;
} else if (CompressMethod.LH7.equalsIgnoreCase(method)) {
return 256;
} else if (CompressMethod.LZ4.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (CompressMethod.LH0.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (CompressMethod.LHD.equalsIgnoreCase(method)) {
throw new IllegalArgumentException(method + " means no compress.");
} else if (method == null) {
throw new NullPointerException("method");
} else {
throw new IllegalArgumentException("Unknown compress method. " + method);
}
}
// ------------------------------------------------------------------
// shared method
/**
* property に設定された生成式を利用して method の圧縮法でデータを圧縮し、outに出力するストリームを構築する。
*
* @param out 圧縮データ出力先のストリーム
* @param method 圧縮法識別子
* @param property 各圧縮形式に対応した符号器の生成式等が含まれるプロパティ
* @return method の圧縮法でデータを圧縮し、outに出力するストリーム
*/
public static OutputStream connectEncoder(final OutputStream out, final String method, final Properties property) {
final String key = "lha." + CompressMethod.getCore(method) + ".encoder";
String generator = property.getProperty(key);
if (generator == null) {
generator = LhaProperty.getProperty(key);
}
String packages = property.getProperty("lha.packages");
if (packages == null) {
packages = LhaProperty.getProperty("lha.packages");
}
final Hashtable substitute = new Hashtable();
substitute.put("out", out);
return (OutputStream) LhaProperty.parse(generator, substitute, packages);
}
/**
* property に設定された生成式を利用して in から method の圧縮法で圧縮されたデータを解凍し 供給する入力ストリームを構築する。
*
* @param in 圧縮データを供給するストリーム
* @param method 圧縮法識別子
* @param property 各圧縮形式に対応した復号器の生成式等が含まれるプロパティ
* @return in から method の圧縮法で圧縮されたデータを解凍し 供給する入力ストリームを構築する。
*/
public static InputStream connectDecoder(final InputStream in, final String method, final Properties property, final long length) {
final String key = "lha." + CompressMethod.getCore(method) + ".decoder";
String generator = property.getProperty(key);
if (generator == null) {
generator = LhaProperty.getProperty(key);
}
String packages = property.getProperty("lha.packages");
if (packages == null) {
packages = LhaProperty.getProperty("lha.packages");
}
final Hashtable substitute = new Hashtable();
substitute.put("in", in);
substitute.put("length", new Long(length));
return (InputStream) LhaProperty.parse(generator, substitute, packages);
}
// ------------------------------------------------------------------
// local method
/**
* 圧縮法識別子 の前後の '-' を取り去って LhaProperty のキー lha.???.encoder / lha.???.decoder の ??? に入る文字列を生成する。
*
* @param method 圧縮法識別子
* @return キーの中心に使える文字列
*/
private static String getCore(final String method) {
if (method.startsWith("-") && method.endsWith("-")) {
return method.substring(1, method.lastIndexOf('-')).toLowerCase();
}
throw new IllegalArgumentException("");
}
} | source cleanup | src/main/java/jp/gr/java_conf/dangan/util/lha/CompressMethod.java | source cleanup | <ide><path>rc/main/java/jp/gr/java_conf/dangan/util/lha/CompressMethod.java
<ide> * @return 辞書サイズ
<ide> */
<ide> public static int toDictionarySize(final String method) {
<del> if (CompressMethod.LZS.equalsIgnoreCase(method)) {
<add> if (LZS.equalsIgnoreCase(method)) {
<ide> return 2048;
<del> } else if (CompressMethod.LZ5.equalsIgnoreCase(method)) {
<add> } else if (LZ5.equalsIgnoreCase(method)) {
<ide> return 4096;
<del> } else if (CompressMethod.LH1.equalsIgnoreCase(method)) {
<add> } else if (LH1.equalsIgnoreCase(method)) {
<ide> return 4096;
<del> } else if (CompressMethod.LH2.equalsIgnoreCase(method)) {
<add> } else if (LH2.equalsIgnoreCase(method)) {
<ide> return 8192;
<del> } else if (CompressMethod.LH3.equalsIgnoreCase(method)) {
<add> } else if (LH3.equalsIgnoreCase(method)) {
<ide> return 8192;
<del> } else if (CompressMethod.LH4.equalsIgnoreCase(method)) {
<add> } else if (LH4.equalsIgnoreCase(method)) {
<ide> return 4096;
<del> } else if (CompressMethod.LH5.equalsIgnoreCase(method)) {
<add> } else if (LH5.equalsIgnoreCase(method)) {
<ide> return 8192;
<del> } else if (CompressMethod.LH6.equalsIgnoreCase(method)) {
<add> } else if (LH6.equalsIgnoreCase(method)) {
<ide> return 32768;
<del> } else if (CompressMethod.LH7.equalsIgnoreCase(method)) {
<add> } else if (LH7.equalsIgnoreCase(method)) {
<ide> return 65536;
<del> } else if (CompressMethod.LZ4.equalsIgnoreCase(method)) {
<del> throw new IllegalArgumentException(method + " means no compress.");
<del> } else if (CompressMethod.LH0.equalsIgnoreCase(method)) {
<del> throw new IllegalArgumentException(method + " means no compress.");
<del> } else if (CompressMethod.LHD.equalsIgnoreCase(method)) {
<add> } else if (LZ4.equalsIgnoreCase(method)) {
<add> throw new IllegalArgumentException(method + " means no compress.");
<add> } else if (LH0.equalsIgnoreCase(method)) {
<add> throw new IllegalArgumentException(method + " means no compress.");
<add> } else if (LHD.equalsIgnoreCase(method)) {
<ide> throw new IllegalArgumentException(method + " means no compress.");
<ide> } else if (method == null) {
<ide> throw new NullPointerException("method");
<ide> * @return 圧縮/非圧縮
<ide> */
<ide> public static int toThreshold(final String method) {
<del> if (CompressMethod.LZS.equalsIgnoreCase(method)) {
<add> if (LZS.equalsIgnoreCase(method)) {
<ide> return 2;
<del> } else if (CompressMethod.LZ5.equalsIgnoreCase(method)) {
<del> return 3;
<del> } else if (CompressMethod.LH1.equalsIgnoreCase(method)) {
<del> return 3;
<del> } else if (CompressMethod.LH2.equalsIgnoreCase(method)) {
<del> return 3;
<del> } else if (CompressMethod.LH3.equalsIgnoreCase(method)) {
<del> return 3;
<del> } else if (CompressMethod.LH4.equalsIgnoreCase(method)) {
<del> return 3;
<del> } else if (CompressMethod.LH5.equalsIgnoreCase(method)) {
<del> return 3;
<del> } else if (CompressMethod.LH6.equalsIgnoreCase(method)) {
<del> return 3;
<del> } else if (CompressMethod.LH7.equalsIgnoreCase(method)) {
<del> return 3;
<del> } else if (CompressMethod.LZ4.equalsIgnoreCase(method)) {
<del> throw new IllegalArgumentException(method + " means no compress.");
<del> } else if (CompressMethod.LH0.equalsIgnoreCase(method)) {
<del> throw new IllegalArgumentException(method + " means no compress.");
<del> } else if (CompressMethod.LHD.equalsIgnoreCase(method)) {
<add> } else if (LZ5.equalsIgnoreCase(method)) {
<add> return 3;
<add> } else if (LH1.equalsIgnoreCase(method)) {
<add> return 3;
<add> } else if (LH2.equalsIgnoreCase(method)) {
<add> return 3;
<add> } else if (LH3.equalsIgnoreCase(method)) {
<add> return 3;
<add> } else if (LH4.equalsIgnoreCase(method)) {
<add> return 3;
<add> } else if (LH5.equalsIgnoreCase(method)) {
<add> return 3;
<add> } else if (LH6.equalsIgnoreCase(method)) {
<add> return 3;
<add> } else if (LH7.equalsIgnoreCase(method)) {
<add> return 3;
<add> } else if (LZ4.equalsIgnoreCase(method)) {
<add> throw new IllegalArgumentException(method + " means no compress.");
<add> } else if (LH0.equalsIgnoreCase(method)) {
<add> throw new IllegalArgumentException(method + " means no compress.");
<add> } else if (LHD.equalsIgnoreCase(method)) {
<ide> throw new IllegalArgumentException(method + " means no compress.");
<ide> } else if (method == null) {
<ide> throw new NullPointerException("method");
<ide> * @return 最大一致長
<ide> */
<ide> public static int toMaxMatch(final String method) {
<del> if (CompressMethod.LZS.equalsIgnoreCase(method)) {
<add> if (LZS.equalsIgnoreCase(method)) {
<ide> return 17;
<del> } else if (CompressMethod.LZ5.equalsIgnoreCase(method)) {
<add> } else if (LZ5.equalsIgnoreCase(method)) {
<ide> return 18;
<del> } else if (CompressMethod.LH1.equalsIgnoreCase(method)) {
<add> } else if (LH1.equalsIgnoreCase(method)) {
<ide> return 60;
<del> } else if (CompressMethod.LH2.equalsIgnoreCase(method)) {
<del> return 256;
<del> } else if (CompressMethod.LH3.equalsIgnoreCase(method)) {
<del> return 256;
<del> } else if (CompressMethod.LH4.equalsIgnoreCase(method)) {
<del> return 256;
<del> } else if (CompressMethod.LH5.equalsIgnoreCase(method)) {
<del> return 256;
<del> } else if (CompressMethod.LH6.equalsIgnoreCase(method)) {
<del> return 256;
<del> } else if (CompressMethod.LH7.equalsIgnoreCase(method)) {
<del> return 256;
<del> } else if (CompressMethod.LZ4.equalsIgnoreCase(method)) {
<del> throw new IllegalArgumentException(method + " means no compress.");
<del> } else if (CompressMethod.LH0.equalsIgnoreCase(method)) {
<del> throw new IllegalArgumentException(method + " means no compress.");
<del> } else if (CompressMethod.LHD.equalsIgnoreCase(method)) {
<add> } else if (LH2.equalsIgnoreCase(method)) {
<add> return 256;
<add> } else if (LH3.equalsIgnoreCase(method)) {
<add> return 256;
<add> } else if (LH4.equalsIgnoreCase(method)) {
<add> return 256;
<add> } else if (LH5.equalsIgnoreCase(method)) {
<add> return 256;
<add> } else if (LH6.equalsIgnoreCase(method)) {
<add> return 256;
<add> } else if (LH7.equalsIgnoreCase(method)) {
<add> return 256;
<add> } else if (LZ4.equalsIgnoreCase(method)) {
<add> throw new IllegalArgumentException(method + " means no compress.");
<add> } else if (LH0.equalsIgnoreCase(method)) {
<add> throw new IllegalArgumentException(method + " means no compress.");
<add> } else if (LHD.equalsIgnoreCase(method)) {
<ide> throw new IllegalArgumentException(method + " means no compress.");
<ide> } else if (method == null) {
<ide> throw new NullPointerException("method");
<ide> * @return method の圧縮法でデータを圧縮し、outに出力するストリーム
<ide> */
<ide> public static OutputStream connectEncoder(final OutputStream out, final String method, final Properties property) {
<del> final String key = "lha." + CompressMethod.getCore(method) + ".encoder";
<add> final String key = "lha." + getCore(method) + ".encoder";
<ide>
<ide> String generator = property.getProperty(key);
<ide> if (generator == null) {
<ide> packages = LhaProperty.getProperty("lha.packages");
<ide> }
<ide>
<del> final Hashtable substitute = new Hashtable();
<add> final Hashtable<String, Object> substitute = new Hashtable<String, Object>();
<ide> substitute.put("out", out);
<ide>
<ide> return (OutputStream) LhaProperty.parse(generator, substitute, packages);
<ide> * @return in から method の圧縮法で圧縮されたデータを解凍し 供給する入力ストリームを構築する。
<ide> */
<ide> public static InputStream connectDecoder(final InputStream in, final String method, final Properties property, final long length) {
<del> final String key = "lha." + CompressMethod.getCore(method) + ".decoder";
<add> final String key = "lha." + getCore(method) + ".decoder";
<ide>
<ide> String generator = property.getProperty(key);
<ide> if (generator == null) {
<ide> packages = LhaProperty.getProperty("lha.packages");
<ide> }
<ide>
<del> final Hashtable substitute = new Hashtable();
<add> final Hashtable<String, Object> substitute = new Hashtable<String, Object>();
<ide> substitute.put("in", in);
<ide> substitute.put("length", new Long(length));
<ide> |
|
Java | apache-2.0 | 85fee8dc240b141163b1ecbbe03528945541d775 | 0 | krzysztof-magosa/encog-java-core,spradnyesh/encog-java-core,SpenceSouth/encog-java-core,danilodesousacubas/encog-java-core,SpenceSouth/encog-java-core,spradnyesh/encog-java-core,danilodesousacubas/encog-java-core,krzysztof-magosa/encog-java-core,ThiagoGarciaAlves/encog-java-core,Crespo911/encog-java-core,Crespo911/encog-java-core,ThiagoGarciaAlves/encog-java-core | /*
* Encog(tm) Core v2.5 - Java Version
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
* Copyright 2008-2010 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.neural.networks.training.cross;
import org.encog.engine.network.flat.FlatNetwork;
import org.encog.neural.data.folded.FoldedDataSet;
import org.encog.neural.networks.training.Train;
/**
* Train using K-Fold cross validation. Each iteration will train a number of
* times equal to the number of folds - 1. Each of these sub iterations will
* train all of the data minus the fold. The fold is used to validate.
*
* Therefore, you are seeing an error that reflects data that was not always
* used as part of training. This should give you a better error result based on
* how the network will perform on non-trained data.(validation).
*
* The cross validation trainer must be provided with some other sort of
* trainer, perhaps RPROP, to actually perform the training. The training data
* must be the FoldedDataSet. The folded dataset can wrap most other training
* sets.
*
* @author jheaton
*
*/
public class CrossValidationKFold extends CrossTraining {
/**
* The underlying trainer to use. This trainer does the actual training.
*/
private final Train train;
private final NetworkFold[] networks;
private final FlatNetwork flatNetwork;
/**
* Construct a cross validation trainer.
*
* @param train
* The training
* @param k
* The number of folds.
*/
public CrossValidationKFold(final Train train, final int k) {
super(train.getNetwork(), (FoldedDataSet) train.getTraining());
this.train = train;
getFolded().fold(k);
this.flatNetwork = train.getNetwork().getStructure().getFlat();
this.networks = new NetworkFold[k];
for (int i = 0; i < networks.length; i++) {
this.networks[i] = new NetworkFold(flatNetwork);
}
}
/**
* Perform one iteration.
*/
@Override
public void iteration() {
double error = 0;
for (int valFold = 0; valFold < getFolded().getNumFolds(); valFold++) {
// restore the correct network
this.networks[valFold].copyToNetwork(this.flatNetwork);
// train with non-validation folds
for (int curFold = 0; curFold < getFolded().getNumFolds(); curFold++) {
if (curFold != valFold) {
getFolded().setCurrentFold(curFold);
this.train.iteration();
}
}
// evaluate with the validation fold
getFolded().setCurrentFold(valFold);
double e = this.flatNetwork.calculateError(getFolded());
//System.out.println("Fold " + valFold + ", " + e);
error += e;
this.networks[valFold].copyFromNetwork(this.flatNetwork);
}
setError(error / getFolded().getNumFolds());
}
}
| src/org/encog/neural/networks/training/cross/CrossValidationKFold.java | /*
* Encog(tm) Core v2.5 - Java Version
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
* Copyright 2008-2010 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.neural.networks.training.cross;
import org.encog.engine.network.flat.FlatNetwork;
import org.encog.neural.data.folded.FoldedDataSet;
import org.encog.neural.networks.training.Train;
/**
* Train using K-Fold cross validation. Each iteration will train a number of
* times equal to the number of folds - 1. Each of these sub iterations will
* train all of the data minus the fold. The fold is used to validate.
*
* Therefore, you are seeing an error that reflects data that was not always
* used as part of training. This should give you a better error result based on
* how the network will perform on non-trained data.(validation).
*
* The cross validation trainer must be provided with some other sort of
* trainer, perhaps RPROP, to actually perform the training. The training data
* must be the FoldedDataSet. The folded dataset can wrap most other training
* sets.
*
* @author jheaton
*
*/
public class CrossValidationKFold extends CrossTraining {
/**
* The underlying trainer to use. This trainer does the actual training.
*/
private final Train train;
private final NetworkFold[] networks;
private final FlatNetwork flatNetwork;
/**
* Construct a cross validation trainer.
*
* @param train
* The training
* @param k
* The number of folds.
*/
public CrossValidationKFold(final Train train, final int k) {
super(train.getNetwork(), (FoldedDataSet) train.getTraining());
this.train = train;
getFolded().fold(k);
this.flatNetwork = train.getNetwork().getStructure().getFlat();
this.networks = new NetworkFold[k];
for (int i = 0; i < networks.length; i++) {
this.networks[i] = new NetworkFold(flatNetwork);
}
}
/**
* Perform one iteration.
*/
@Override
public void iteration() {
double error = 0;
for (int valFold = 0; valFold < getFolded().getNumFolds(); valFold++) {
// restore the correct network
this.networks[valFold].copyToNetwork(this.flatNetwork);
// train with non-validation folds
for (int curFold = 0; curFold < getFolded().getNumFolds(); curFold++) {
if (curFold != valFold) {
getFolded().setCurrentFold(curFold);
this.train.iteration();
}
}
// evaluate with the validation fold
getFolded().setCurrentFold(valFold);
double e = this.flatNetwork.calculateError(getFolded());
System.out.println("Fold " + valFold + ", " + e);
error += e;
this.networks[valFold].copyFromNetwork(this.flatNetwork);
}
setError(error / getFolded().getNumFolds());
}
}
| Removed debug statement
git-svn-id: f699b99be54c313e643266d5dd560bc939300b59@2260 f90f6e9a-ac51-0410-b353-d1b83c6f6923
| src/org/encog/neural/networks/training/cross/CrossValidationKFold.java | Removed debug statement | <ide><path>rc/org/encog/neural/networks/training/cross/CrossValidationKFold.java
<ide> // evaluate with the validation fold
<ide> getFolded().setCurrentFold(valFold);
<ide> double e = this.flatNetwork.calculateError(getFolded());
<del> System.out.println("Fold " + valFold + ", " + e);
<add> //System.out.println("Fold " + valFold + ", " + e);
<ide> error += e;
<ide> this.networks[valFold].copyFromNetwork(this.flatNetwork);
<ide> } |
|
Java | mit | 5e21737636fd749507bcf51fa8498b1374332780 | 0 | elliottsj/ftw-android | package com.afollestad.silk.cache;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* @author Aidan Follestad (afollestad)
*/
class SilkCacheManagerBase<T extends SilkComparable> {
protected SilkCacheManagerBase(Context context, String cacheName, File cacheDir) {
mContext = context;
if (cacheName == null || cacheName.trim().isEmpty())
cacheName = "default";
if (cacheDir == null)
cacheDir = new File(Environment.getExternalStorageDirectory(), "Silk");
if (!cacheDir.exists())
cacheDir.mkdirs();
cacheFile = new File(cacheDir, cacheName.toLowerCase() + ".cache");
}
private Context mContext;
protected List<T> buffer;
private final File cacheFile;
protected Handler mHandler;
protected boolean isChanged;
protected CacheLimiter mLimiter;
protected void log(String message) {
Log.d("SilkCacheManager", getCacheFile().getName() + ": " + message);
}
public final CacheLimiter getLimiter() {
return mLimiter;
}
protected Context getContext() {
return mContext;
}
/**
* Checks whether or not the manager has been commited.
* <p/>
* If it has, you cannot commit again until you re-initialize the manager
* or make a call to {@link com.afollestad.silk.cache.SilkCacheManager#forceReload()}.
*/
public final boolean isCommitted() {
return buffer == null;
}
/**
* Gets whether or not the cache has been changed since it was initialized.
*/
public final boolean isChanged() {
return isChanged;
}
protected void runPriorityThread(Runnable runnable) {
Thread t = new Thread(runnable);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
protected final Handler getHandler() {
if (mHandler == null)
mHandler = new Handler();
return mHandler;
}
protected File getCacheFile() {
return cacheFile;
}
protected void reloadIfNecessary() {
if (isExpired()) {
log("The cache has expired, wiping...");
buffer = new ArrayList<T>();
getContext().getSharedPreferences("[silk-cache-expirations]", Context.MODE_PRIVATE)
.edit().remove(getCacheFile().getName()).commit();
getCacheFile().delete();
return;
} else if (buffer != null) return;
buffer = loadItems();
}
/**
* Gets the items currently stored in the cache manager's buffer; the buffer is loaded when the manager
* is instantiated, cleared when it commits, and reloaded when needed.
*/
public List<T> read() {
reloadIfNecessary();
return buffer;
}
private boolean isExpired() {
SharedPreferences prefs = mContext.getSharedPreferences("[silk-cache-expirations]", Context.MODE_PRIVATE);
if (!prefs.contains(getCacheFile().getName())) return false;
long dateTime = prefs.getLong(getCacheFile().getName(), 0);
long now = Calendar.getInstance().getTimeInMillis();
return dateTime <= now;
}
/**
* Checks whether or not an expiration has been set to the cache.
*/
public final boolean hasExpiration() {
SharedPreferences prefs = mContext.getSharedPreferences("[silk-cache-expirations]", Context.MODE_PRIVATE);
return prefs.contains(getCacheFile().getName());
}
private List<T> loadItems() {
try {
final List<T> results = new ArrayList<T>();
if (cacheFile.exists()) {
FileInputStream fileInputStream = new FileInputStream(cacheFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
while (true) {
try {
final T item = (T) objectInputStream.readObject();
if (item != null) results.add(item);
} catch (EOFException eof) {
break;
}
}
objectInputStream.close();
}
log("Read " + results.size() + " items from " + cacheFile.getName());
return results;
} catch (Exception e) {
e.printStackTrace();
log("Error loading items: " + e.getMessage());
}
return null;
}
/**
* Commits all changes to the cache file. This is from the calling thread.
*/
public void commit() throws Exception {
if (isCommitted()) {
throw new IllegalStateException("The SilkCacheManager has already committed, you must re-initialize the manager or call forceReload().");
} else if (!isChanged()) {
throw new IllegalStateException("The SilkCacheManager has not been modified since initialization.");
} else if (buffer.size() == 0) {
if (cacheFile.exists()) {
log("Deleting: " + cacheFile.getName());
cacheFile.delete();
}
return;
}
// Trim off older items
if (mLimiter != null && buffer.size() > mLimiter.getSize()) {
log("Cache (" + buffer.size() + ") is larger than size limit (" + mLimiter.getSize() + "), trimming...");
while (buffer.size() > mLimiter.getSize()) {
if (mLimiter.getMode() == CacheLimiter.TrimMode.TOP) buffer.remove(0);
else buffer.remove(buffer.size() - 1);
}
}
int subtraction = 0;
FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
for (T item : buffer) {
if (item.shouldIgnore()) {
subtraction++;
continue;
}
objectOutputStream.writeObject(item);
}
objectOutputStream.close();
log("Committed " + (buffer.size() - subtraction) + " items to " + cacheFile.getName());
buffer = null;
isChanged = false;
}
/**
* Commits all changes to the cache file. This is run on a separate thread and the results are posted to a callback.
*/
public void commitAsync(final SilkCacheManager.SimpleCommitCallback callback) {
final Handler handler = getHandler();
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
commit();
if (callback != null) {
handler.post(new Runnable() {
@Override
public void run() {
if (callback instanceof SilkCacheManager.CommitCallback)
((SilkCacheManager.CommitCallback) callback).onCommitted();
}
});
}
} catch (final Exception e) {
e.printStackTrace();
log("Cache commit error: " + e.getMessage());
if (callback != null) {
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onError(e);
}
});
}
}
}
});
}
} | library/src/com/afollestad/silk/cache/SilkCacheManagerBase.java | package com.afollestad.silk.cache;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* @author Aidan Follestad (afollestad)
*/
class SilkCacheManagerBase<T extends SilkComparable> {
protected SilkCacheManagerBase(Context context, String cacheName, File cacheDir) {
mContext = context;
if (cacheName == null || cacheName.trim().isEmpty())
cacheName = "default";
if (cacheDir == null)
cacheDir = new File(Environment.getExternalStorageDirectory(), "Silk");
if (!cacheDir.exists())
cacheDir.mkdirs();
cacheFile = new File(cacheDir, cacheName.toLowerCase() + ".cache");
}
private Context mContext;
protected List<T> buffer;
private final File cacheFile;
protected Handler mHandler;
protected boolean isChanged;
protected CacheLimiter mLimiter;
protected void log(String message) {
Log.d("SilkCacheManager", getCacheFile().getName() + ": " + message);
}
public final CacheLimiter getLimiter() {
return mLimiter;
}
protected Context getContext() {
return mContext;
}
/**
* Checks whether or not the manager has been commited.
* <p/>
* If it has, you cannot commit again until you re-initialize the manager
* or make a call to {@link com.afollestad.silk.cache.SilkCacheManager#forceReload()}.
*/
public final boolean isCommitted() {
return buffer == null;
}
/**
* Gets whether or not the cache has been changed since it was initialized.
*/
public final boolean isChanged() {
return isChanged;
}
protected void runPriorityThread(Runnable runnable) {
Thread t = new Thread(runnable);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
protected final Handler getHandler() {
if (mHandler == null)
mHandler = new Handler();
return mHandler;
}
protected File getCacheFile() {
return cacheFile;
}
protected void reloadIfNecessary() {
if (isExpired()) {
log("The cache has expired, wiping...");
buffer = new ArrayList<T>();
getContext().getSharedPreferences("[silk-cache-expirations]", Context.MODE_PRIVATE)
.edit().remove(getCacheFile().getName()).commit();
getCacheFile().delete();
return;
} else if (buffer != null) return;
buffer = loadItems();
}
/**
* Gets the items currently stored in the cache manager's buffer; the buffer is loaded when the manager
* is instantiated, cleared when it commits, and reloaded when needed.
*/
public List<T> read() {
reloadIfNecessary();
return buffer;
}
private boolean isExpired() {
SharedPreferences prefs = mContext.getSharedPreferences("[silk-cache-expirations]", Context.MODE_PRIVATE);
if (!prefs.contains(getCacheFile().getName())) return false;
long dateTime = prefs.getLong(getCacheFile().getName(), 0);
long now = Calendar.getInstance().getTimeInMillis();
return dateTime <= now;
}
private List<T> loadItems() {
try {
final List<T> results = new ArrayList<T>();
if (cacheFile.exists()) {
FileInputStream fileInputStream = new FileInputStream(cacheFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
while (true) {
try {
final T item = (T) objectInputStream.readObject();
if (item != null) results.add(item);
} catch (EOFException eof) {
break;
}
}
objectInputStream.close();
}
log("Read " + results.size() + " items from " + cacheFile.getName());
return results;
} catch (Exception e) {
e.printStackTrace();
log("Error loading items: " + e.getMessage());
}
return null;
}
/**
* Commits all changes to the cache file. This is from the calling thread.
*/
public void commit() throws Exception {
if (isCommitted()) {
throw new IllegalStateException("The SilkCacheManager has already committed, you must re-initialize the manager or call forceReload().");
} else if (!isChanged()) {
throw new IllegalStateException("The SilkCacheManager has not been modified since initialization.");
} else if (buffer.size() == 0) {
if (cacheFile.exists()) {
log("Deleting: " + cacheFile.getName());
cacheFile.delete();
}
return;
}
// Trim off older items
if (mLimiter != null && buffer.size() > mLimiter.getSize()) {
log("Cache (" + buffer.size() + ") is larger than size limit (" + mLimiter.getSize() + "), trimming...");
while (buffer.size() > mLimiter.getSize()) {
if (mLimiter.getMode() == CacheLimiter.TrimMode.TOP) buffer.remove(0);
else buffer.remove(buffer.size() - 1);
}
}
int subtraction = 0;
FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
for (T item : buffer) {
if (item.shouldIgnore()) {
subtraction++;
continue;
}
objectOutputStream.writeObject(item);
}
objectOutputStream.close();
log("Committed " + (buffer.size() - subtraction) + " items to " + cacheFile.getName());
buffer = null;
isChanged = false;
}
/**
* Commits all changes to the cache file. This is run on a separate thread and the results are posted to a callback.
*/
public void commitAsync(final SilkCacheManager.SimpleCommitCallback callback) {
final Handler handler = getHandler();
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
commit();
if (callback != null) {
handler.post(new Runnable() {
@Override
public void run() {
if (callback instanceof SilkCacheManager.CommitCallback)
((SilkCacheManager.CommitCallback) callback).onCommitted();
}
});
}
} catch (final Exception e) {
e.printStackTrace();
log("Cache commit error: " + e.getMessage());
if (callback != null) {
getHandler().post(new Runnable() {
@Override
public void run() {
callback.onError(e);
}
});
}
}
}
});
}
} | Updates.
| library/src/com/afollestad/silk/cache/SilkCacheManagerBase.java | Updates. | <ide><path>ibrary/src/com/afollestad/silk/cache/SilkCacheManagerBase.java
<ide> long dateTime = prefs.getLong(getCacheFile().getName(), 0);
<ide> long now = Calendar.getInstance().getTimeInMillis();
<ide> return dateTime <= now;
<add> }
<add>
<add> /**
<add> * Checks whether or not an expiration has been set to the cache.
<add> */
<add> public final boolean hasExpiration() {
<add> SharedPreferences prefs = mContext.getSharedPreferences("[silk-cache-expirations]", Context.MODE_PRIVATE);
<add> return prefs.contains(getCacheFile().getName());
<ide> }
<ide>
<ide> private List<T> loadItems() { |
|
JavaScript | mit | 9616e9b3cb10fc2e0b8d3244abbfb4f0810c198c | 0 | TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control | import { h } from 'hyperapp'
import nipplejs from 'nipplejs'
import {throttle} from 'lodash'
export const Joystick = ({mode, motors}) =>
<div class={(mode==='drive') ? 'joystick' : 'joystick joystick-hide'} oncreate={(el) => joystick(el, motors)}>
<img class="joystick_image" src={require("../../../img/ui/right-krzyz.svg")}/>
</div>
const joystick = (element, motors) => {
let manager = nipplejs.create({
zone: element,
mode: 'static',
position: {left: '50%', top: '50%'},
size: element.clientHeight,
dataOnly: true
});
let timer_id = 0;
manager.on('start', function (evt, nipple) {
console.log(evt);
nipple.on('move', (evt, data) => motorsThrottled(evt, data));
});
let motorsThrottled = throttle((evt, data) => {
motors.set(Math.round(data.distance), convertToArrOfDirections(data.direction));
console.log(Math.round(data.distance), convertToArrOfDirections(data.direction));
}, 100, { 'trailing': false });
manager.on('end', function(evt, nipple) {
console.log(evt);
clearInterval(timer_id);
// nipple.off('start move end dir plain');
});
const convertToArrOfDirections = (direction) => {
if (typeof direction !== "undefined" ) {
if (direction.angle === "up") {
return [0, 0, 0, 0];
} else if (direction.angle === "down") {
return [1, 1, 1, 1];
} else if (direction.angle === "left") {
return [1, 0, 1, 0];
} else if (direction.angle === "right") {
return [0, 1, 0, 1];
}
} else {
return [0, 0, 0, 0];
}
}
} | client/src/js/view/components/joystick.js | import { h } from 'hyperapp'
import nipplejs from 'nipplejs'
export const Joystick = ({mode, motors}) =>
<div class={(mode==='drive') ? 'joystick' : 'joystick joystick-hide'} oncreate={(el) => joystick(el, motors)}>
<img class="joystick_image" src={require("../../../img/ui/right-krzyz.svg")}/>
</div>
const joystick = (element, motors) => {
let manager = nipplejs.create({
zone: element,
mode: 'static',
position: {left: '50%', top: '50%'},
size: element.clientHeight,
dataOnly: true
});
manager.on('start', function(evt, nipple) {
console.log(evt);
nipple.on('move', function(evt, data) {
motors.set(Math.round(data.distance), convertToArrOfDirections(data.direction));
console.log(Math.round(data.distance), convertToArrOfDirections(data.direction));
});
}).on('end', function(evt, nipple) {
console.log(evt);
// nipple.off('start move end dir plain');
});
const convertToArrOfDirections = (direction) => {
if (typeof direction !== "undefined" ) {
if (direction.angle === "up") {
return [0, 0, 0, 0];
} else if (direction.angle === "down") {
return [1, 1, 1, 1];
} else if (direction.angle === "left") {
return [1, 0, 1, 0];
} else if (direction.angle === "right") {
return [0, 1, 0, 1];
}
} else {
return [0, 0, 0, 0];
}
}
} | add throttling to joystick
| client/src/js/view/components/joystick.js | add throttling to joystick | <ide><path>lient/src/js/view/components/joystick.js
<ide> import { h } from 'hyperapp'
<ide> import nipplejs from 'nipplejs'
<del>
<add>import {throttle} from 'lodash'
<ide>
<ide> export const Joystick = ({mode, motors}) =>
<ide> <div class={(mode==='drive') ? 'joystick' : 'joystick joystick-hide'} oncreate={(el) => joystick(el, motors)}>
<ide> dataOnly: true
<ide> });
<ide>
<del> manager.on('start', function(evt, nipple) {
<del> console.log(evt);
<del> nipple.on('move', function(evt, data) {
<add> let timer_id = 0;
<ide>
<del> motors.set(Math.round(data.distance), convertToArrOfDirections(data.direction));
<del> console.log(Math.round(data.distance), convertToArrOfDirections(data.direction));
<del>
<add> manager.on('start', function (evt, nipple) {
<add> console.log(evt);
<ide>
<del> });
<del> }).on('end', function(evt, nipple) {
<add> nipple.on('move', (evt, data) => motorsThrottled(evt, data));
<add>
<add> });
<add>
<add> let motorsThrottled = throttle((evt, data) => {
<add> motors.set(Math.round(data.distance), convertToArrOfDirections(data.direction));
<add> console.log(Math.round(data.distance), convertToArrOfDirections(data.direction));
<add> }, 100, { 'trailing': false });
<add>
<add> manager.on('end', function(evt, nipple) {
<ide> console.log(evt);
<add> clearInterval(timer_id);
<ide> // nipple.off('start move end dir plain');
<ide> });
<ide> |
|
Java | apache-2.0 | 5435a4a0d35f7ba21590bb1415f12651ca0d02b2 | 0 | ChinaQuants/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics,nssales/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,ChinaQuants/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,codeaudit/OG-Platform | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.web.bundle;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import com.opengamma.util.ArgumentChecker;
/**
* Manages the CSS/Javascript bundles.
* <p>
* This acts as the root of the tree.
*/
public class BundleManager {
/**
* The map of bundles by ID.
*/
private Map<String, Bundle> _bundleMap = new ConcurrentHashMap<String, Bundle>();
/**
* Creates an instance.
*/
public BundleManager() {
}
//-------------------------------------------------------------------------
/**
* Looks up a bundle by ID.
*
* @param id the ID to look up, not null
* @return the bundle, null if not found
*/
public Bundle getBundle(String id) {
return _bundleMap.get(id);
}
/**
* Adds a bundle to the manager.
*
* @param bundle the bundle to add, not null
*/
public void addBundle(Bundle bundle) {
ArgumentChecker.notNull(bundle, "bundle");
ArgumentChecker.notNull(bundle.getId(), "bundle.id");
// recursively add children as well
for (Bundle loop : bundle.getAllBundles()) {
_bundleMap.put(loop.getId(), loop);
}
}
/**
* Gets the set of all bundle IDs.
*
* @return the unmodifiable bundle ID set, not null
*/
public Set<String> getBundleIds() {
return Collections.unmodifiableSet(_bundleMap.keySet());
}
@Override
public String toString() {
ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE);
for (Entry<String, Bundle> entry : _bundleMap.entrySet()) {
builder.append(entry.getKey(), entry.getValue().toString());
}
return builder.toString();
// return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
| projects/OG-Web/src/main/java/com/opengamma/web/bundle/BundleManager.java | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.web.bundle;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.opengamma.util.ArgumentChecker;
/**
* Manages the CSS/Javascript bundles.
* <p>
* This acts as the root of the tree.
*/
public class BundleManager {
/**
* The map of bundles by ID.
*/
private Map<String, Bundle> _bundleMap = new ConcurrentHashMap<String, Bundle>();
/**
* Creates an instance.
*/
public BundleManager() {
}
//-------------------------------------------------------------------------
/**
* Looks up a bundle by ID.
*
* @param id the ID to look up, not null
* @return the bundle, null if not found
*/
public Bundle getBundle(String id) {
return _bundleMap.get(id);
}
/**
* Adds a bundle to the manager.
*
* @param bundle the bundle to add, not null
*/
public void addBundle(Bundle bundle) {
ArgumentChecker.notNull(bundle, "bundle");
ArgumentChecker.notNull(bundle.getId(), "bundle.id");
// recursively add children as well
for (Bundle loop : bundle.getAllBundles()) {
_bundleMap.put(loop.getId(), loop);
}
}
/**
* Gets the set of all bundle IDs.
*
* @return the unmodifiable bundle ID set, not null
*/
public Set<String> getBundleIds() {
return Collections.unmodifiableSet(_bundleMap.keySet());
}
}
| Add toString to BundleManager for debug purpose
| projects/OG-Web/src/main/java/com/opengamma/web/bundle/BundleManager.java | Add toString to BundleManager for debug purpose | <ide><path>rojects/OG-Web/src/main/java/com/opengamma/web/bundle/BundleManager.java
<ide>
<ide> import java.util.Collections;
<ide> import java.util.Map;
<add>import java.util.Map.Entry;
<ide> import java.util.Set;
<ide> import java.util.concurrent.ConcurrentHashMap;
<add>
<add>import org.apache.commons.lang.builder.ToStringBuilder;
<add>import org.apache.commons.lang.builder.ToStringStyle;
<ide>
<ide> import com.opengamma.util.ArgumentChecker;
<ide>
<ide> return Collections.unmodifiableSet(_bundleMap.keySet());
<ide> }
<ide>
<add> @Override
<add> public String toString() {
<add> ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE);
<add> for (Entry<String, Bundle> entry : _bundleMap.entrySet()) {
<add> builder.append(entry.getKey(), entry.getValue().toString());
<add> }
<add> return builder.toString();
<add>// return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | c61152202c8e9959e5c09b45ec44e83e8fd140e1 | 0 | hmunfru/fiware-paas,Fiware/cloud.PaaS,Fiware/cloud.PaaS,telefonicaid/fiware-paas,telefonicaid/fiware-paas,hmunfru/fiware-paas,telefonicaid/fiware-paas,hmunfru/fiware-paas,Fiware/cloud.PaaS | /**
* (c) Copyright 2013 Telefonica, I+D. Printed in Spain (Europe). All Rights Reserved.<br>
* The copyright to the software program(s) is property of Telefonica I+D. The program(s) may be used and or copied only
* with the express written consent of Telefonica I+D or in accordance with the terms and conditions stipulated in the
* agreement/contract under which the program(s) have been supplied.
*/
package com.telefonica.euro_iaas.paasmanager.rest.resources;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import com.telefonica.euro_iaas.commons.dao.EntityNotFoundException;
import com.telefonica.euro_iaas.commons.dao.InvalidEntityException;
import com.telefonica.euro_iaas.paasmanager.exception.AlreadyExistEntityException;
import com.telefonica.euro_iaas.paasmanager.exception.EnvironmentInstanceNotFoundException;
import com.telefonica.euro_iaas.paasmanager.exception.InfrastructureException;
import com.telefonica.euro_iaas.paasmanager.exception.InvalidEnvironmentRequestException;
import com.telefonica.euro_iaas.paasmanager.manager.EnvironmentManager;
import com.telefonica.euro_iaas.paasmanager.manager.impl.EnvironmentManagerImpl;
import com.telefonica.euro_iaas.paasmanager.model.ClaudiaData;
import com.telefonica.euro_iaas.paasmanager.model.Environment;
import com.telefonica.euro_iaas.paasmanager.model.Tier;
import com.telefonica.euro_iaas.paasmanager.model.dto.EnvironmentDto;
import com.telefonica.euro_iaas.paasmanager.model.dto.PaasManagerUser;
import com.telefonica.euro_iaas.paasmanager.model.dto.TierDto;
import com.telefonica.euro_iaas.paasmanager.model.searchcriteria.EnvironmentSearchCriteria;
import com.telefonica.euro_iaas.paasmanager.rest.util.ExtendedOVFUtil;
import com.telefonica.euro_iaas.paasmanager.rest.util.OVFGeneration;
import com.telefonica.euro_iaas.paasmanager.rest.validation.EnvironmentResourceValidator;
import com.telefonica.euro_iaas.paasmanager.util.SystemPropertiesProvider;
/**
* default Environment implementation
*
* @author Henar Mu�oz
*/
@Path("/catalog/org/{org}/vdc/{vdc}/environment")
@Component
@Scope("request")
public class EnvironmentResourceImpl implements EnvironmentResource {
public static final int ERROR_NOT_FOUND = 404;
public static final int ERROR_REQUEST = 500;
private EnvironmentManager environmentManager;
private SystemPropertiesProvider systemPropertiesProvider;
private EnvironmentResourceValidator environmentResourceValidator;
private OVFGeneration ovfGeneration;
private ExtendedOVFUtil extendedOVFUtil;
private static Logger log = Logger.getLogger(EnvironmentManagerImpl.class);
/**
* Convert a list of tierDtos to a list of Tiers
*
* @return
*/
private Set<Tier> convertToTiers(Set<TierDto> tierDtos, String environmentName, String vdc) {
Set<Tier> tiers = new HashSet<Tier>();
for (TierDto tierDto: tierDtos) {
Tier tier = tierDto.fromDto(vdc);
// tier.setSecurity_group("sg_"
// +environmentName+"_"+vdc+"_"+tier.getName());
tiers.add(tier);
}
return tiers;
}
public void delete(String org, String vdc, String envName) throws EnvironmentInstanceNotFoundException,
InvalidEntityException, InvalidEnvironmentRequestException, AlreadyExistEntityException {
ClaudiaData claudiaData = new ClaudiaData(org, vdc, envName);
environmentResourceValidator.validateDelete(envName, vdc, systemPropertiesProvider);
addCredentialsToClaudiaData(claudiaData);
try {
Environment env = environmentManager.load(envName, vdc);
environmentManager.destroy(claudiaData, env);
} catch (EntityNotFoundException e) {
throw new WebApplicationException(e, ERROR_NOT_FOUND);
} catch (InfrastructureException e) {
throw new WebApplicationException(e, ERROR_REQUEST);
}
}
/* private List<Environment> filterEqualTiers(List<Environment> environments) {
// List<Tier> tierResult = new ArrayList<Tier>();
List<Environment> result = new ArrayList<Environment>();
for (Environment environment : environments) {
Set<Tier> tierResult = new HashSet<Tier>();
Set<Tier> tiers = environment.getTiers();
for (Tier tier: tiers) {
int i=0;
List<Tier> tierAux = new ArrayList<Tier>();
for (int j = i + 1; j < tiers.size(); j++) {
tierAux.add(tiers.get(j));
}
if (!tierAux.contains(tier)) {
tierResult.add(tier);
}
i++;
}
environment.setTiers(tierResult);
result.add(environment);
}
return result;
}*/
public List<EnvironmentDto> findAll(String org, String vdc, Integer page, Integer pageSize, String orderBy,
String orderType) {
EnvironmentSearchCriteria criteria = new EnvironmentSearchCriteria();
criteria.setVdc(vdc);
criteria.setOrg(org);
if (page != null && pageSize != null) {
criteria.setPage(page);
criteria.setPageSize(pageSize);
}
if (!StringUtils.isEmpty(orderBy)) {
criteria.setOrderBy(orderBy);
}
if (!StringUtils.isEmpty(orderType)) {
criteria.setOrderBy(orderType);
}
List<Environment> env = environmentManager.findByCriteria(criteria);
// Solve the tier-environment duplicity appeared at database due to hibernate problems
// List<Environment> envs = filterEqualTiers(env);
List<EnvironmentDto> envsDto = new ArrayList<EnvironmentDto>();
for (int i = 0; i < env.size(); i++) {
envsDto.add(env.get(i).toDto());
}
return envsDto;
}
public PaasManagerUser getCredentials() {
if (systemPropertiesProvider.getProperty(SystemPropertiesProvider.CLOUD_SYSTEM).equals("FIWARE")) {
return (PaasManagerUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
} else {
return null;
}
}
/**
* Add PaasManagerUser to claudiaData.
*
* @param claudiaData
*/
public void addCredentialsToClaudiaData(ClaudiaData claudiaData) {
if (systemPropertiesProvider.getProperty(SystemPropertiesProvider.CLOUD_SYSTEM).equals("FIWARE")) {
claudiaData.setUser(extendedOVFUtil.getCredentials());
claudiaData.getUser().setTenantId(claudiaData.getVdc());
}
}
public void insert(String org, String vdc, EnvironmentDto environmentDto)
throws InvalidEnvironmentRequestException, AlreadyExistEntityException, InvalidEntityException {
ClaudiaData claudiaData = new ClaudiaData(org, vdc, environmentDto.getName());
log.debug("Create a environment " + environmentDto.getName() + " " + environmentDto.getDescription() + " "
+ environmentDto.getVdc() + " " + environmentDto.getOrg() + " " + environmentDto.getTierDtos());
// try
// {
addCredentialsToClaudiaData(claudiaData);
environmentResourceValidator.validateCreate(claudiaData, environmentDto, vdc, systemPropertiesProvider);
/*
* } catch (InvalidEnvironmentRequestException e) { throw new WebApplicationException(e, ERROR_REQUEST); } catch
* (AlreadyExistEntityException e) { throw new WebApplicationException(e, ERROR_REQUEST); } catch
* (InvalidEntityException e) { throw new WebApplicationException(e, ERROR_REQUEST); }
*/
Environment environment = new Environment();
environment.setName(environmentDto.getName());
environment.setDescription(environmentDto.getDescription());
/*
* String payload = ovfGeneration.createOvf(environmentDto); environment.setOvf(payload);
*/
if (environmentDto.getTierDtos() != null) {
environment.setTiers(convertToTiers(environmentDto.getTierDtos(), environment.getName(), vdc));
}
environment.setOrg(org);
environment.setVdc(vdc);
// try {
environmentManager.create(claudiaData, environment);
// } catch (InvalidEnvironmentRequestException e) {
// TODO Auto-generated catch block
// throw new WebApplicationException(e.getCause(), ERROR_REQUEST);
// }
}
public EnvironmentDto load(String org, String vdc, String name) throws EnvironmentInstanceNotFoundException {
EnvironmentSearchCriteria criteria = new EnvironmentSearchCriteria();
criteria.setVdc(vdc);
criteria.setOrg(org);
criteria.setEnvironmentName(name);
List<Environment> env = environmentManager.findByCriteria(criteria);
// Solve the tier-environment duplicity appeared at database due to hibernate problems
// List<Environment> envs = filterEqualTiers(env);
if (env == null || env.size() == 0) {
throw new WebApplicationException(new EntityNotFoundException(Environment.class, "Environmetn " + name
+ " not found", ""), ERROR_NOT_FOUND);
} else {
EnvironmentDto envDto = env.get(0).toDto();
// EnvironmentDto envDto = env.get(0).toDto();
return envDto;
}
/*
* try { return environmentManager.load(name, vdc).toDto(); } catch (EntityNotFoundException e) { throw new
* EnvironmentInstanceNotFoundException (e); }
*/
}
public void setEnvironmentManager(EnvironmentManager environmentManager) {
this.environmentManager = environmentManager;
}
public void setEnvironmentResourceValidator(EnvironmentResourceValidator environmentResourceValidator) {
this.environmentResourceValidator = environmentResourceValidator;
}
/**
* @param ovfGeneration
* the ovfGeneration to set
*/
public void setOvfGeneration(OVFGeneration ovfGeneration) {
this.ovfGeneration = ovfGeneration;
}
/**
* @param systemPropertiesProvider
* the systemPropertiesProvider to set
*/
public void setSystemPropertiesProvider(SystemPropertiesProvider systemPropertiesProvider) {
this.systemPropertiesProvider = systemPropertiesProvider;
}
public ExtendedOVFUtil getExtendedOVFUtil() {
return extendedOVFUtil;
}
public void setExtendedOVFUtil(ExtendedOVFUtil extendedOVFUtil) {
this.extendedOVFUtil = extendedOVFUtil;
}
}
| rest-api/src/main/java/com/telefonica/euro_iaas/paasmanager/rest/resources/EnvironmentResourceImpl.java | /**
* (c) Copyright 2013 Telefonica, I+D. Printed in Spain (Europe). All Rights Reserved.<br>
* The copyright to the software program(s) is property of Telefonica I+D. The program(s) may be used and or copied only
* with the express written consent of Telefonica I+D or in accordance with the terms and conditions stipulated in the
* agreement/contract under which the program(s) have been supplied.
*/
package com.telefonica.euro_iaas.paasmanager.rest.resources;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import com.telefonica.euro_iaas.commons.dao.EntityNotFoundException;
import com.telefonica.euro_iaas.commons.dao.InvalidEntityException;
import com.telefonica.euro_iaas.paasmanager.exception.AlreadyExistEntityException;
import com.telefonica.euro_iaas.paasmanager.exception.EnvironmentInstanceNotFoundException;
import com.telefonica.euro_iaas.paasmanager.exception.InfrastructureException;
import com.telefonica.euro_iaas.paasmanager.exception.InvalidEnvironmentRequestException;
import com.telefonica.euro_iaas.paasmanager.manager.EnvironmentManager;
import com.telefonica.euro_iaas.paasmanager.manager.impl.EnvironmentManagerImpl;
import com.telefonica.euro_iaas.paasmanager.model.ClaudiaData;
import com.telefonica.euro_iaas.paasmanager.model.Environment;
import com.telefonica.euro_iaas.paasmanager.model.Tier;
import com.telefonica.euro_iaas.paasmanager.model.dto.EnvironmentDto;
import com.telefonica.euro_iaas.paasmanager.model.dto.PaasManagerUser;
import com.telefonica.euro_iaas.paasmanager.model.dto.TierDto;
import com.telefonica.euro_iaas.paasmanager.model.searchcriteria.EnvironmentSearchCriteria;
import com.telefonica.euro_iaas.paasmanager.rest.util.ExtendedOVFUtil;
import com.telefonica.euro_iaas.paasmanager.rest.util.OVFGeneration;
import com.telefonica.euro_iaas.paasmanager.rest.validation.EnvironmentResourceValidator;
import com.telefonica.euro_iaas.paasmanager.util.SystemPropertiesProvider;
/**
* default Environment implementation
*
* @author Henar Mu�oz
*/
@Path("/catalog/org/{org}/vdc/{vdc}/environment")
@Component
@Scope("request")
public class EnvironmentResourceImpl implements EnvironmentResource {
public static final int ERROR_NOT_FOUND = 404;
public static final int ERROR_REQUEST = 500;
private EnvironmentManager environmentManager;
private SystemPropertiesProvider systemPropertiesProvider;
private EnvironmentResourceValidator environmentResourceValidator;
private OVFGeneration ovfGeneration;
private ExtendedOVFUtil extendedOVFUtil;
private static Logger log = Logger.getLogger(EnvironmentManagerImpl.class);
/**
* Convert a list of tierDtos to a list of Tiers
*
* @return
*/
private Set<Tier> convertToTiers(Set<TierDto> tierDtos, String environmentName, String vdc) {
Set<Tier> tiers = new HashSet<Tier>();
for (TierDto tierDto: tierDtos) {
Tier tier = tierDto.fromDto(vdc);
// tier.setSecurity_group("sg_"
// +environmentName+"_"+vdc+"_"+tier.getName());
tiers.add(tier);
}
return tiers;
}
public void delete(String org, String vdc, String envName) throws EnvironmentInstanceNotFoundException,
InvalidEntityException, InvalidEnvironmentRequestException, AlreadyExistEntityException {
ClaudiaData claudiaData = new ClaudiaData(org, vdc, envName);
environmentResourceValidator.validateDelete(envName, vdc, systemPropertiesProvider);
addCredentialsToClaudiaData(claudiaData);
try {
Environment env = environmentManager.load(envName, vdc);
environmentManager.destroy(claudiaData, env);
} catch (EntityNotFoundException e) {
throw new WebApplicationException(e, ERROR_NOT_FOUND);
} catch (InfrastructureException e) {
throw new WebApplicationException(e, ERROR_REQUEST);
}
}
/* private List<Environment> filterEqualTiers(List<Environment> environments) {
// List<Tier> tierResult = new ArrayList<Tier>();
List<Environment> result = new ArrayList<Environment>();
for (Environment environment : environments) {
Set<Tier> tierResult = new HashSet<Tier>();
Set<Tier> tiers = environment.getTiers();
for (Tier tier: tiers) {
int i=0;
List<Tier> tierAux = new ArrayList<Tier>();
for (int j = i + 1; j < tiers.size(); j++) {
tierAux.add(tiers.get(j));
}
if (!tierAux.contains(tier)) {
tierResult.add(tier);
}
i++;
}
environment.setTiers(tierResult);
result.add(environment);
}
return result;
}*/
public List<EnvironmentDto> findAll(String org, String vdc, Integer page, Integer pageSize, String orderBy,
String orderType) {
EnvironmentSearchCriteria criteria = new EnvironmentSearchCriteria();
criteria.setVdc(vdc);
criteria.setOrg(org);
if (page != null && pageSize != null) {
criteria.setPage(page);
criteria.setPageSize(pageSize);
}
if (!StringUtils.isEmpty(orderBy)) {
criteria.setOrderBy(orderBy);
}
if (!StringUtils.isEmpty(orderType)) {
criteria.setOrderBy(orderType);
}
List<Environment> env = environmentManager.findByCriteria(criteria);
// Solve the tier-environment duplicity appeared at database due to hibernate problems
// List<Environment> envs = filterEqualTiers(env);
List<EnvironmentDto> envsDto = new ArrayList<EnvironmentDto>();
for (int i = 0; i < env.size(); i++) {
envsDto.add(env.get(i).toDto());
}
return envsDto;
}
public PaasManagerUser getCredentials() {
if (systemPropertiesProvider.getProperty(SystemPropertiesProvider.CLOUD_SYSTEM).equals("FIWARE")) {
return (PaasManagerUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
} else {
return null;
}
}
/**
* Add PaasManagerUser to claudiaData.
*
* @param claudiaData
*/
public void addCredentialsToClaudiaData(ClaudiaData claudiaData) {
if (systemPropertiesProvider.getProperty(SystemPropertiesProvider.CLOUD_SYSTEM).equals("FIWARE")) {
claudiaData.setUser(extendedOVFUtil.getCredentials());
claudiaData.getUser().setTenantId(claudiaData.getVdc());
}
}
public void insert(String org, String vdc, EnvironmentDto environmentDto)
throws InvalidEnvironmentRequestException, AlreadyExistEntityException, InvalidEntityException {
ClaudiaData claudiaData = new ClaudiaData(org, vdc, environmentDto.getName());
log.debug("Create a environment " + environmentDto.getName() + " " + environmentDto.getDescription() + " "
+ environmentDto.getVdc() + " " + environmentDto.getOrg() + " " + environmentDto.getTierDtos());
// try
// {
environmentResourceValidator.validateCreate(claudiaData, environmentDto, vdc, systemPropertiesProvider);
/*
* } catch (InvalidEnvironmentRequestException e) { throw new WebApplicationException(e, ERROR_REQUEST); } catch
* (AlreadyExistEntityException e) { throw new WebApplicationException(e, ERROR_REQUEST); } catch
* (InvalidEntityException e) { throw new WebApplicationException(e, ERROR_REQUEST); }
*/
addCredentialsToClaudiaData(claudiaData);
Environment environment = new Environment();
environment.setName(environmentDto.getName());
environment.setDescription(environmentDto.getDescription());
/*
* String payload = ovfGeneration.createOvf(environmentDto); environment.setOvf(payload);
*/
if (environmentDto.getTierDtos() != null) {
environment.setTiers(convertToTiers(environmentDto.getTierDtos(), environment.getName(), vdc));
}
environment.setOrg(org);
environment.setVdc(vdc);
// try {
environmentManager.create(claudiaData, environment);
// } catch (InvalidEnvironmentRequestException e) {
// TODO Auto-generated catch block
// throw new WebApplicationException(e.getCause(), ERROR_REQUEST);
// }
}
public EnvironmentDto load(String org, String vdc, String name) throws EnvironmentInstanceNotFoundException {
EnvironmentSearchCriteria criteria = new EnvironmentSearchCriteria();
criteria.setVdc(vdc);
criteria.setOrg(org);
criteria.setEnvironmentName(name);
List<Environment> env = environmentManager.findByCriteria(criteria);
// Solve the tier-environment duplicity appeared at database due to hibernate problems
// List<Environment> envs = filterEqualTiers(env);
if (env == null || env.size() == 0) {
throw new WebApplicationException(new EntityNotFoundException(Environment.class, "Environmetn " + name
+ " not found", ""), ERROR_NOT_FOUND);
} else {
EnvironmentDto envDto = env.get(0).toDto();
// EnvironmentDto envDto = env.get(0).toDto();
return envDto;
}
/*
* try { return environmentManager.load(name, vdc).toDto(); } catch (EntityNotFoundException e) { throw new
* EnvironmentInstanceNotFoundException (e); }
*/
}
public void setEnvironmentManager(EnvironmentManager environmentManager) {
this.environmentManager = environmentManager;
}
public void setEnvironmentResourceValidator(EnvironmentResourceValidator environmentResourceValidator) {
this.environmentResourceValidator = environmentResourceValidator;
}
/**
* @param ovfGeneration
* the ovfGeneration to set
*/
public void setOvfGeneration(OVFGeneration ovfGeneration) {
this.ovfGeneration = ovfGeneration;
}
/**
* @param systemPropertiesProvider
* the systemPropertiesProvider to set
*/
public void setSystemPropertiesProvider(SystemPropertiesProvider systemPropertiesProvider) {
this.systemPropertiesProvider = systemPropertiesProvider;
}
public ExtendedOVFUtil getExtendedOVFUtil() {
return extendedOVFUtil;
}
public void setExtendedOVFUtil(ExtendedOVFUtil extendedOVFUtil) {
this.extendedOVFUtil = extendedOVFUtil;
}
}
| adding credentials to ClaudiaData before validations to ensure a full request with envDto including tierDto, productReleaseDtos works
| rest-api/src/main/java/com/telefonica/euro_iaas/paasmanager/rest/resources/EnvironmentResourceImpl.java | adding credentials to ClaudiaData before validations to ensure a full request with envDto including tierDto, productReleaseDtos works | <ide><path>est-api/src/main/java/com/telefonica/euro_iaas/paasmanager/rest/resources/EnvironmentResourceImpl.java
<ide>
<ide> // try
<ide> // {
<add> addCredentialsToClaudiaData(claudiaData);
<ide> environmentResourceValidator.validateCreate(claudiaData, environmentDto, vdc, systemPropertiesProvider);
<ide> /*
<ide> * } catch (InvalidEnvironmentRequestException e) { throw new WebApplicationException(e, ERROR_REQUEST); } catch
<ide> * (AlreadyExistEntityException e) { throw new WebApplicationException(e, ERROR_REQUEST); } catch
<ide> * (InvalidEntityException e) { throw new WebApplicationException(e, ERROR_REQUEST); }
<ide> */
<del>
<del> addCredentialsToClaudiaData(claudiaData);
<ide>
<ide> Environment environment = new Environment();
<ide> environment.setName(environmentDto.getName()); |
|
Java | apache-2.0 | 682ab5dae2525f2c5a3890dd4e56cceb3e36179e | 0 | DarkPhoenixs/message-queue-client-framework | /*
* Copyright 2015-2016 Dark Phoenixs (Open-Source Organization).
*
* 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.darkphoenixs.kafka.producer;
import org.darkphoenixs.kafka.core.KafkaDestination;
import org.darkphoenixs.kafka.core.KafkaMessageTemplate;
import org.darkphoenixs.mq.exception.MQException;
import org.darkphoenixs.mq.producer.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>Title: AbstractProducer</p>
* <p>Description: 生产者抽象类</p>
*
* @author Victor.Zxy
* @version 1.0
* @see Producer
* @since 2015-06-01
*/
public abstract class AbstractProducer<K, V> implements Producer<V> {
/**
* logger
*/
protected Logger logger = LoggerFactory.getLogger(getClass());
/**
* messageTemplate
*/
private KafkaMessageTemplate<K, V> messageTemplate;
/**
* destination
*/
private KafkaDestination destination;
/**
* @since 1.2.3 producerKey
*/
private String producerKey;
/**
* @return the messageTemplate
*/
public KafkaMessageTemplate<K, V> getMessageTemplate() {
return messageTemplate;
}
/**
* @param messageTemplate the messageTemplate to set
*/
public void setMessageTemplate(KafkaMessageTemplate<K, V> messageTemplate) {
this.messageTemplate = messageTemplate;
}
/**
* @return the destination
*/
public KafkaDestination getDestination() {
return destination;
}
/**
* @param destination the destination to set
*/
public void setDestination(KafkaDestination destination) {
this.destination = destination;
}
@Override
public void send(V message) throws MQException {
try {
V obj = doSend(message);
messageTemplate.convertAndSend(destination, obj);
} catch (Exception e) {
throw new MQException(e);
}
logger.debug("Send Success, ProducerKey : " + this.getProducerKey()
+ " , Message : " + message);
}
/**
* <p>sendWithKey</p>
* <p>发送消息带标识</p>
*
* @param key 标识
* @param message 消息
* @throws MQException
* @since 1.3.0
*/
public void sendWithKey(K key, V message) throws MQException {
try {
V obj = doSend(message);
messageTemplate.convertAndSendWithKey(destination, key, obj);
} catch (Exception e) {
throw new MQException(e);
}
logger.debug("Send Success, ProducerKey : " + this.getProducerKey()
+ " , MessageKey : " + key + " , Message : " + message);
}
@Override
public String getProducerKey() throws MQException {
if (this.producerKey != null)
return this.producerKey;
return destination.getDestinationName();
}
/**
* @param producerKey the producerKey to set
* @since 1.2.3
*/
public void setProducerKey(String producerKey) {
this.producerKey = producerKey;
}
/**
* <p>Title: doSend</p>
* <p>Description: 消息发送方法</p>
*
* @param message 消息
* @return 消息
* @throws MQException MQ异常
*/
protected abstract V doSend(V message) throws MQException;
}
| src/main/java/org/darkphoenixs/kafka/producer/AbstractProducer.java | /*
* Copyright 2015-2016 Dark Phoenixs (Open-Source Organization).
*
* 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.darkphoenixs.kafka.producer;
import org.darkphoenixs.kafka.core.KafkaDestination;
import org.darkphoenixs.kafka.core.KafkaMessageTemplate;
import org.darkphoenixs.mq.exception.MQException;
import org.darkphoenixs.mq.producer.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>Title: AbstractProducer</p>
* <p>Description: 生产者抽象类</p>
*
* @author Victor.Zxy
* @version 1.0
* @see Producer
* @since 2015-06-01
*/
public abstract class AbstractProducer<K, V> implements Producer<V> {
/**
* logger
*/
protected Logger logger = LoggerFactory.getLogger(getClass());
/**
* messageTemplate
*/
private KafkaMessageTemplate<K, V> messageTemplate;
/**
* destination
*/
private KafkaDestination destination;
/**
* @since 1.2.3 producerKey
*/
private String producerKey;
/**
* @return the messageTemplate
*/
public KafkaMessageTemplate<K, V> getMessageTemplate() {
return messageTemplate;
}
/**
* @param messageTemplate the messageTemplate to set
*/
public void setMessageTemplate(KafkaMessageTemplate<K, V> messageTemplate) {
this.messageTemplate = messageTemplate;
}
/**
* @return the destination
*/
public KafkaDestination getDestination() {
return destination;
}
/**
* @param destination the destination to set
*/
public void setDestination(KafkaDestination destination) {
this.destination = destination;
}
@Override
public void send(V message) throws MQException {
try {
V obj = doSend(message);
messageTemplate.convertAndSend(destination, obj);
} catch (Exception e) {
throw new MQException(e);
}
logger.debug("Send Success, ProducerKey : " + this.getProducerKey()
+ " , Message : " + message);
}
/**
* <p>sendWithKey</p>
* <p>发送消息带标识</p>
*
* @param key 标识
* @param message 消息
* @throws MQException
* @since 1.3.0
*/
public void sendWithKey(K key, V message) throws MQException {
try {
messageTemplate.convertAndSendWithKey(destination, key, message);
} catch (Exception e) {
throw new MQException(e);
}
logger.debug("Send Success, ProducerKey : " + this.getProducerKey()
+ " , MessageKey : " + key + " , Message : " + message);
}
@Override
public String getProducerKey() throws MQException {
if (this.producerKey != null)
return this.producerKey;
return destination.getDestinationName();
}
/**
* @param producerKey the producerKey to set
* @since 1.2.3
*/
public void setProducerKey(String producerKey) {
this.producerKey = producerKey;
}
/**
* <p>Title: doSend</p>
* <p>Description: 消息发送方法</p>
*
* @param message 消息
* @return 消息
* @throws MQException MQ异常
*/
protected abstract V doSend(V message) throws MQException;
}
| fix issue
| src/main/java/org/darkphoenixs/kafka/producer/AbstractProducer.java | fix issue | <ide><path>rc/main/java/org/darkphoenixs/kafka/producer/AbstractProducer.java
<ide>
<ide> logger.debug("Send Success, ProducerKey : " + this.getProducerKey()
<ide> + " , Message : " + message);
<del>
<ide> }
<ide>
<ide> /**
<ide> public void sendWithKey(K key, V message) throws MQException {
<ide>
<ide> try {
<del> messageTemplate.convertAndSendWithKey(destination, key, message);
<add>
<add> V obj = doSend(message);
<add>
<add> messageTemplate.convertAndSendWithKey(destination, key, obj);
<ide>
<ide> } catch (Exception e) {
<ide> |
|
Java | bsd-3-clause | 1ebbe4567eb4c79cb5809b3584ab9ddb675bd90f | 0 | NCIP/catissue-core,krishagni/openspecimen,asamgir/openspecimen,krishagni/openspecimen,NCIP/catissue-core,krishagni/openspecimen,asamgir/openspecimen,NCIP/catissue-core,asamgir/openspecimen | /*
* Created on Aug 10, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package edu.wustl.catissuecore.exception;
/**
* @author kapil_kaveeshwar
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class AssignDataException extends Exception
{
public AssignDataException()
{
}
public AssignDataException(Exception e)
{
}
}
| WEB-INF/src/edu/wustl/catissuecore/exception/AssignDataException.java | /*
* Created on Aug 10, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package edu.wustl.catissuecore.exception;
/**
* @author kapil_kaveeshwar
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class AssignDataException extends Exception
{
}
| *** empty log message ***
SVN-Revision: 1021
| WEB-INF/src/edu/wustl/catissuecore/exception/AssignDataException.java | *** empty log message *** | <ide><path>EB-INF/src/edu/wustl/catissuecore/exception/AssignDataException.java
<ide> */
<ide> public class AssignDataException extends Exception
<ide> {
<del>
<add> public AssignDataException()
<add> {
<add>
<add> }
<add> public AssignDataException(Exception e)
<add> {
<add>
<add> }
<ide> } |
|
Java | lgpl-2.1 | 854723d72bf7417cc707a081e3c608c4fb1729e1 | 0 | patczar/exist,ambs/exist,windauer/exist,adamretter/exist,hungerburg/exist,RemiKoutcherawy/exist,joewiz/exist,dizzzz/exist,wshager/exist,patczar/exist,ambs/exist,lcahlander/exist,patczar/exist,windauer/exist,adamretter/exist,ambs/exist,adamretter/exist,lcahlander/exist,jensopetersen/exist,olvidalo/exist,wolfgangmm/exist,eXist-db/exist,jessealama/exist,patczar/exist,zwobit/exist,dizzzz/exist,ljo/exist,jessealama/exist,windauer/exist,wshager/exist,joewiz/exist,zwobit/exist,jensopetersen/exist,wolfgangmm/exist,MjAbuz/exist,lcahlander/exist,ljo/exist,MjAbuz/exist,lcahlander/exist,kohsah/exist,ambs/exist,jessealama/exist,eXist-db/exist,patczar/exist,RemiKoutcherawy/exist,olvidalo/exist,kohsah/exist,MjAbuz/exist,wshager/exist,wshager/exist,joewiz/exist,jensopetersen/exist,kohsah/exist,eXist-db/exist,wshager/exist,hungerburg/exist,windauer/exist,opax/exist,adamretter/exist,RemiKoutcherawy/exist,jensopetersen/exist,eXist-db/exist,zwobit/exist,zwobit/exist,zwobit/exist,lcahlander/exist,wshager/exist,adamretter/exist,RemiKoutcherawy/exist,zwobit/exist,shabanovd/exist,ljo/exist,wolfgangmm/exist,MjAbuz/exist,dizzzz/exist,ljo/exist,kohsah/exist,RemiKoutcherawy/exist,jessealama/exist,shabanovd/exist,dizzzz/exist,opax/exist,jensopetersen/exist,windauer/exist,olvidalo/exist,ljo/exist,opax/exist,opax/exist,shabanovd/exist,ambs/exist,opax/exist,ambs/exist,wolfgangmm/exist,shabanovd/exist,olvidalo/exist,hungerburg/exist,MjAbuz/exist,joewiz/exist,MjAbuz/exist,ljo/exist,lcahlander/exist,hungerburg/exist,dizzzz/exist,jensopetersen/exist,joewiz/exist,wolfgangmm/exist,kohsah/exist,eXist-db/exist,RemiKoutcherawy/exist,joewiz/exist,wolfgangmm/exist,adamretter/exist,eXist-db/exist,windauer/exist,jessealama/exist,patczar/exist,kohsah/exist,hungerburg/exist,shabanovd/exist,dizzzz/exist,olvidalo/exist,jessealama/exist,shabanovd/exist | /*
* eXist Open Source Native XML Database
* Copyright (C) 2001-03 Wolfgang M. Meier
* [email protected]
* http://exist.sourceforge.net
*
* 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.xquery;
import java.io.IOException;
import java.io.Reader;
import java.net.MalformedURLException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.TreeMap;
import org.apache.log4j.Logger;
import org.exist.EXistException;
import org.exist.collections.Collection;
import org.exist.dom.BinaryDocument;
import org.exist.dom.DocumentImpl;
import org.exist.dom.DocumentSet;
import org.exist.dom.NodeProxy;
import org.exist.dom.QName;
import org.exist.dom.SymbolTable;
import org.exist.memtree.MemTreeBuilder;
import org.exist.security.Permission;
import org.exist.security.PermissionDeniedException;
import org.exist.security.User;
import org.exist.source.DBSource;
import org.exist.source.Source;
import org.exist.source.SourceFactory;
import org.exist.storage.DBBroker;
import org.exist.storage.lock.Lock;
import org.exist.util.Collations;
import org.exist.util.Configuration;
import org.exist.util.LockException;
import org.exist.xquery.parser.XQueryLexer;
import org.exist.xquery.parser.XQueryParser;
import org.exist.xquery.parser.XQueryTreeParser;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.NodeValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceIterator;
import org.exist.xquery.value.Type;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import antlr.collections.AST;
/**
* The current XQuery execution context. Contains the static as well
* as the dynamic XQuery context components.
*
* @author Wolfgang Meier ([email protected])
*/
public class XQueryContext {
private static final String JAVA_URI_START = "java:";
private static final String XMLDB_URI_START = "xmldb:exist://";
public final static String XML_NS = "http://www.w3.org/XML/1998/namespace";
public final static String SCHEMA_NS = "http://www.w3.org/2001/XMLSchema";
public final static String SCHEMA_DATATYPES_NS =
"http://www.w3.org/2001/XMLSchema-datatypes";
public final static String SCHEMA_INSTANCE_NS =
"http://www.w3.org/2001/XMLSchema-instance";
public final static String XPATH_DATATYPES_NS =
"http://www.w3.org/2003/05/xpath-datatypes";
public final static String XQUERY_LOCAL_NS =
"http://www.w3.org/2003/08/xquery-local-functions";
public final static String EXIST_NS =
"http://exist.sourceforge.net/NS/exist";
private final static Logger LOG = Logger.getLogger(XQueryContext.class);
private static final String TEMP_STORE_ERROR = "Error occurred while storing temporary data";
private static final HashMap moduleClasses = new HashMap();
// Static namespace/prefix mappings
protected HashMap namespaces;
// Local in-scope namespace/prefix mappings in the current context
protected HashMap inScopeNamespaces = new HashMap();
// Static prefix/namespace mappings
protected HashMap prefixes;
// Local prefix/namespace mappings in the current context
protected HashMap inScopePrefixes = new HashMap();
// Local namespace stack
protected Stack namespaceStack = new Stack();
// Known user defined functions in the local module
protected TreeMap declaredFunctions = new TreeMap();
// Globally declared variables
protected TreeMap globalVariables = new TreeMap();
// The last element in the linked list of local in-scope variables
protected LocalVariable lastVar = null;
protected Stack contextStack = new Stack();
// The current size of the variable stack
protected int variableStackSize = 0;
// Unresolved references to user defined functions
protected Stack forwardReferences = new Stack();
// List of pragmas declared for this query
protected List pragmas = null;
/**
* the watchdog object assigned to this query
*
* @uml.property name="watchdog"
* @uml.associationEnd multiplicity="(1 1)"
*/
protected XQueryWatchDog watchdog;
/**
* Loaded modules.
*/
protected HashMap modules = new HashMap();
/**
* The set of statically known documents specified as
* an array of paths to documents and collections.
*/
protected String[] staticDocumentPaths = null;
/**
* The actual set of statically known documents. This
* will be generated on demand from staticDocumentPaths.
*/
protected DocumentSet staticDocuments = null;
/**
* The main database broker object providing access
* to storage and indexes. Every XQuery has its own
* DBBroker object.
*/
protected DBBroker broker;
protected String baseURI = "";
protected boolean baseURISetInProlog = false;
protected String moduleLoadPath = ".";
protected String defaultFunctionNamespace = Module.BUILTIN_FUNCTION_NS;
/**
* The default collation URI
*/
private String defaultCollation = Collations.CODEPOINT;
/**
* Default Collator. Will be null for the default unicode codepoint collation.
*/
private Collator defaultCollator = null;
/**
* Set to true to enable XPath 1.0
* backwards compatibility.
*/
private boolean backwardsCompatible = true;
/**
* Should whitespace inside node constructors be stripped?
*/
private boolean stripWhitespace = true;
/**
* The position of the currently processed item in the context
* sequence. This field has to be set on demand, for example,
* before calling the fn:position() function.
*/
private int contextPosition = 0;
/**
* The builder used for creating in-memory document
* fragments
*/
private MemTreeBuilder builder = null;
/**
* Stack for temporary document fragments
*/
private Stack fragmentStack = new Stack();
/**
* The root of the expression tree
*/
private Expression rootExpression;
/**
* Flag to indicate that the query should put an exclusive
* lock on all documents involved.
*
* TODO: No longer needed?
*/
private boolean exclusive = false;
/**
* Should all documents loaded by the query be locked?
* If set to true, it is the responsibility of the calling client
* code to unlock documents after the query has completed.
*/
private boolean lockDocumentsOnLoad = false;
/**
* Documents locked during the query.
*/
private DocumentSet lockedDocuments = null;
/**
* The profiler instance used by this context.
*/
private Profiler profiler = new Profiler();
//For holding XQuery Context variables from setXQueryContextVar() and getXQueryContextVar()
HashMap XQueryContextVars = new HashMap();
//set an XQuery Context variable; called by context:set-var()
public void setXQueryContextVar(String name, Object XQvar)
{
XQueryContextVars.put(name, XQvar);
}
//get an XQuery Context variable; called by context:get-var()
public Object getXQueryContextVar(String name)
{
return(XQueryContextVars.get(name));
}
protected XQueryContext() {
builder = new MemTreeBuilder(this);
builder.startDocument();
}
public XQueryContext(DBBroker broker) {
this();
this.broker = broker;
loadDefaults(broker.getConfiguration());
}
/**
* @return true if profiling is enabled for this context.
*/
public boolean isProfilingEnabled() {
return profiler.isEnabled();
}
public boolean isProfilingEnabled(int verbosity) {
return profiler.isEnabled() && profiler.verbosity() >= verbosity;
}
/**
* Returns the {@link Profiler} instance of this context
* if profiling is enabled.
*
* @return the profiler instance.
*/
public Profiler getProfiler() {
return profiler;
}
/**
* Called from the XQuery compiler to set the root expression
* for this context.
*
* @param expr
*/
public void setRootExpression(Expression expr) {
this.rootExpression = expr;
}
/**
* Returns the root expression of the XQuery associated with
* this context.
*
* @return
*/
public Expression getRootExpression() {
return rootExpression;
}
/**
* Declare a user-defined prefix/namespace mapping.
*
* eXist internally keeps a table containing all prefix/namespace
* mappings it found in documents, which have been previously
* stored into the database. These default mappings need not to be
* declared explicitely.
*
* @param prefix
* @param uri
*/
public void declareNamespace(String prefix, String uri) throws XPathException {
if (prefix == null)
prefix = "";
if(uri == null)
uri = "";
if (prefix.equals("xml") || prefix.equals("xmlns"))
throw new XPathException("err:XQST0070: Namespace predefined prefix '" + prefix + "' can not be bound");
if (uri.equals(XML_NS))
throw new XPathException("err:XQST0070: Namespace URI '" + uri + "' must be bound to the 'xml' prefix");
final String prevURI = (String)namespaces.get(prefix);
//This prefix was not bound
if(prevURI == null ) {
//Bind it
if (uri.length() > 0) {
namespaces.put(prefix, uri);
prefixes.put(uri, prefix);
return;
}
//Nothing to bind
else {
//TODO : check the specs : unbinding an NS which is not already bound may be disallowed.
LOG.warn("Unbinding unbound prefix '" + prefix + "'");
}
}
else
//This prefix was bound
{
//Unbind it
if (uri.length() == 0) {
// if an empty namespace is specified,
// remove any existing mapping for this namespace
//TODO : improve, since XML_NS can't be unbound
prefixes.remove(uri);
namespaces.remove(prefix);
return;
}
//Forbids rebinding the *same* prefix in a *different* namespace in this *same* context
if (!uri.equals(prevURI))
throw new XPathException("err:XQST0033: Namespace prefix '" + prefix + "' is already bound to a different uri '" + prevURI + "'");
}
}
public void declareNamespaces(Map namespaceMap) {
Map.Entry entry;
String prefix, uri;
for(Iterator i = namespaceMap.entrySet().iterator(); i.hasNext(); ) {
entry = (Map.Entry)i.next();
prefix = (String)entry.getKey();
uri = (String) entry.getValue();
if(prefix == null)
prefix = "";
if(uri == null)
uri = "";
namespaces.put(prefix, uri);
prefixes.put(uri, prefix);
}
}
/**
* Declare an in-scope namespace. This is called during query execution.
*
* @param prefix
* @param uri
*/
public void declareInScopeNamespace(String prefix, String uri) {
if (prefix == null || uri == null)
throw new IllegalArgumentException("null argument passed to declareNamespace");
if (inScopeNamespaces == null)
inScopeNamespaces = new HashMap();
inScopeNamespaces.put(prefix, uri);
}
/**
* Returns the current default function namespace.
*
* @return
*/
public String getDefaultFunctionNamespace() {
return defaultFunctionNamespace;
}
/**
* Set the default function namespace. By default, this
* points to the namespace for XPath built-in functions.
*
* @param uri
*/
public void setDefaultFunctionNamespace(String uri) {
defaultFunctionNamespace = uri;
}
/**
* Set the default collation to be used by all operators and functions on strings.
* Throws an exception if the collation is unknown or cannot be instantiated.
*
* @param uri
* @throws XPathException
*/
public void setDefaultCollation(String uri) throws XPathException {
if(uri.equals(Collations.CODEPOINT) || uri.equals(Collations.CODEPOINT_SHORT)) {
defaultCollation = Collations.CODEPOINT;
defaultCollator = null;
}
defaultCollator = Collations.getCollationFromURI(this, uri);
defaultCollation = uri;
}
public String getDefaultCollation() {
return defaultCollation;
}
public Collator getCollator(String uri) throws XPathException {
if(uri == null)
return defaultCollator;
return Collations.getCollationFromURI(this, uri);
}
public Collator getDefaultCollator() {
return defaultCollator;
}
/**
* Return the namespace URI mapped to the registered prefix
* or null if the prefix is not registered.
*
* @param prefix
* @return
*/
public String getURIForPrefix(String prefix) {
String ns = (String) namespaces.get(prefix);
if (ns == null)
// try in-scope namespace declarations
return inScopeNamespaces == null
? null
: (String) inScopeNamespaces.get(prefix);
else
return ns;
}
/**
* Return the prefix mapped to the registered URI or
* null if the URI is not registered.
*
* @param uri
* @return
*/
public String getPrefixForURI(String uri) {
String prefix = (String) prefixes.get(uri);
if (prefix == null)
return inScopePrefixes == null ? null : (String) inScopeNamespaces.get(uri);
else
return prefix;
}
/**
* Removes the namespace URI from the prefix/namespace
* mappings table.
*
* @param uri
*/
public void removeNamespace(String uri) {
prefixes.remove(uri);
for (Iterator i = namespaces.values().iterator(); i.hasNext();) {
if (((String) i.next()).equals(uri)) {
i.remove();
return;
}
}
inScopePrefixes.remove(uri);
if (inScopeNamespaces != null) {
for (Iterator i = inScopeNamespaces.values().iterator(); i.hasNext();) {
if (((String) i.next()).equals(uri)) {
i.remove();
return;
}
}
}
}
/**
* Clear all user-defined prefix/namespace mappings.
*/
public void clearNamespaces() {
namespaces.clear();
prefixes.clear();
if (inScopeNamespaces != null) {
inScopeNamespaces.clear();
inScopePrefixes.clear();
}
loadDefaults(broker.getConfiguration());
}
/**
* Set the set of statically known documents for the current
* execution context. These documents will be processed if
* no explicit document set has been set for the current expression
* with fn:doc() or fn:collection().
*
* @param docs
*/
public void setStaticallyKnownDocuments(String[] docs) {
staticDocumentPaths = docs;
}
public void setStaticallyKnownDocuments(DocumentSet set) {
staticDocuments = set;
}
/**
* Get the set of statically known documents.
*
* @return
*/
public DocumentSet getStaticallyKnownDocuments() throws XPathException {
if(staticDocuments != null)
// the document set has already been built, return it
return staticDocuments;
staticDocuments = new DocumentSet();
if(staticDocumentPaths == null)
// no path defined: return all documents in the db
broker.getAllDocuments(staticDocuments);
else {
DocumentImpl doc;
Collection collection;
for(int i = 0; i < staticDocumentPaths.length; i++) {
try {
doc = broker.openDocument(staticDocumentPaths[i], Lock.READ_LOCK);
if(doc != null) {
if(doc.getPermissions().validate(broker.getUser(), Permission.READ)) {
staticDocuments.add(doc);
}
doc.getUpdateLock().release(Lock.READ_LOCK);
} else {
collection = broker.getCollection(staticDocumentPaths[i]);
if(collection != null) {
LOG.debug("reading collection " + staticDocumentPaths[i]);
collection.allDocs(broker, staticDocuments, true, true);
}
}
} catch(PermissionDeniedException e) {
LOG.warn("Permission denied to read resource " + staticDocumentPaths[i] + ". Skipping it.");
}
}
}
return staticDocuments;
}
/**
* Should loaded documents be locked?
*
* @see #setLockDocumentsOnLoad(boolean)
*
* @return
*/
public boolean lockDocumentsOnLoad() {
return lockDocumentsOnLoad;
}
/**
* If lock is true, all documents loaded during query execution
* will be locked. This way, we avoid that query results become
* invalid before the entire result has been processed by the client
* code. All attempts to modify nodes which are part of the result
* set will be blocked.
*
* However, it is the client's responsibility to proper unlock
* all documents once processing is completed.
*
* @param lock
*/
public void setLockDocumentsOnLoad(boolean lock) {
lockDocumentsOnLoad = lock;
if(lock)
lockedDocuments = new DocumentSet();
}
/**
* Returns the set of documents that have been loaded and
* locked during query execution.
*
* @see #setLockDocumentsOnLoad(boolean)
*
* @return
*/
public DocumentSet getLockedDocuments() {
return lockedDocuments;
}
/**
* Release all locks on documents that have been locked
* during query execution.
*
*@see #setLockDocumentsOnLoad(boolean)
*/
public void releaseLockedDocuments() {
if(lockedDocuments != null)
lockedDocuments.unlock(false);
lockDocumentsOnLoad = false;
lockedDocuments = null;
}
/**
* Release all locks on documents not being referenced by the sequence.
* This is called after query execution has completed. Only locks on those
* documents contained in the final result set will be preserved. All other
* locks are released as they are no longer needed.
*
* @param seq
* @return
*/
public DocumentSet releaseUnusedDocuments(Sequence seq) {
if(lockedDocuments == null)
return null;
// determine the set of documents referenced by nodes in the sequence
DocumentSet usedDocs = new DocumentSet();
for(SequenceIterator i = seq.iterate(); i.hasNext(); ) {
Item next = i.nextItem();
if(Type.subTypeOf(next.getType(), Type.NODE)) {
NodeValue node = (NodeValue) next;
if(node.getImplementationType() == NodeValue.PERSISTENT_NODE) {
DocumentImpl doc = ((NodeProxy)node).getDocument();
if(!usedDocs.contains(doc.getDocId()))
usedDocs.add(doc, false);
}
}
}
DocumentSet remaining = new DocumentSet();
for(Iterator i = lockedDocuments.iterator(); i.hasNext(); ) {
DocumentImpl next = (DocumentImpl) i.next();
if(usedDocs.contains(next.getDocId())) {
remaining.add(next);
} else {
// LOG.debug("Releasing lock on " + next.getName());
next.getUpdateLock().release(Lock.READ_LOCK);
}
}
// LOG.debug("Locks remaining: " + remaining.getLength());
lockDocumentsOnLoad = false;
lockedDocuments = null;
return remaining;
}
/**
* Prepare this XQueryContext to be reused. This should be
* called when adding an XQuery to the cache.
*/
public void reset() {
builder = new MemTreeBuilder(this);
builder.startDocument();
staticDocumentPaths = null;
staticDocuments = null;
lastVar = null;
fragmentStack = new Stack();
watchdog.reset();
profiler.reset();
for(Iterator i = modules.values().iterator(); i.hasNext(); ) {
Module module = (Module)i.next();
module.reset();
}
}
/**
* Returns true if whitespace between constructed element nodes
* should be stripped by default.
*
* @return
*/
public boolean stripWhitespace() {
return stripWhitespace;
}
public void setStripWhitespace(boolean strip) {
this.stripWhitespace = strip;
}
/**
* Return an iterator over all built-in modules currently
* registered.
*
* @return
*/
public Iterator getModules() {
return modules.values().iterator();
}
/**
* Get the built-in module registered for the given namespace
* URI.
*
* @param namespaceURI
* @return
*/
public Module getModule(String namespaceURI) {
return (Module) modules.get(namespaceURI);
}
/**
* For compiled expressions: check if the source of any
* module imported by the current query has changed since
* compilation.
*
* @return
*/
public boolean checkModulesValid() {
for(Iterator i = modules.values().iterator(); i.hasNext(); ) {
Module module = (Module)i.next();
if(!module.isInternalModule()) {
if(!((ExternalModule)module).moduleIsValid()) {
LOG.debug("Module with URI " + module.getNamespaceURI() +
" has changed and needs to be reloaded");
return false;
}
}
}
return true;
}
/**
* Load a built-in module from the given class name and assign it to the
* namespace URI. The specified class should be a subclass of
* {@link Module}. The method will try to instantiate the class. If the
* class is not found or an exception is thrown, the method will silently
* fail. The namespace URI has to be equal to the namespace URI declared
* by the module class. Otherwise, the module is not loaded.
*
* @param namespaceURI
* @param moduleClass
*/
public Module loadBuiltInModule(String namespaceURI, String moduleClass) {
Module module = getModule(namespaceURI);
if (module != null) {
// LOG.debug("module " + namespaceURI + " is already present");
return module;
}
try {
Class mClass = (Class) moduleClasses.get(moduleClass);
if (mClass == null) {
mClass = Class.forName(moduleClass);
if (!(Module.class.isAssignableFrom(mClass))) {
LOG.warn(
"failed to load module. "
+ moduleClass
+ " is not an instance of org.exist.xquery.Module.");
return null;
}
moduleClasses.put(moduleClass, mClass);
}
module = (Module) mClass.newInstance();
if (!module.getNamespaceURI().equals(namespaceURI)) {
LOG.warn("the module declares a different namespace URI. Skipping...");
return null;
}
if (getPrefixForURI(module.getNamespaceURI()) == null
&& module.getDefaultPrefix().length() > 0)
declareNamespace(module.getDefaultPrefix(), module.getNamespaceURI());
modules.put(module.getNamespaceURI(), module);
//LOG.debug("module " + module.getNamespaceURI() + " loaded successfully.");
} catch (ClassNotFoundException e) {
//LOG.warn("module class " + moduleClass + " not found. Skipping...");
} catch (InstantiationException e) {
LOG.warn("error while instantiating module class " + moduleClass, e);
} catch (IllegalAccessException e) {
LOG.warn("error while instantiating module class " + moduleClass, e);
} catch (XPathException e) {
LOG.warn("error while instantiating module class " + moduleClass, e);
}
return module;
}
/**
* Declare a user-defined function. All user-defined functions are kept
* in a single hash map.
*
* @param function
* @throws XPathException
*/
public void declareFunction(UserDefinedFunction function) throws XPathException {
declaredFunctions.put(function.getSignature().getFunctionId(), function);
}
/**
* Resolve a user-defined function.
*
* @param name
* @return
* @throws XPathException
*/
public UserDefinedFunction resolveFunction(QName name, int argCount) throws XPathException {
FunctionId id = new FunctionId(name, argCount);
UserDefinedFunction func = (UserDefinedFunction) declaredFunctions.get(id);
return func;
}
public Iterator getSignaturesForFunction(QName name) {
ArrayList signatures = new ArrayList(2);
for (Iterator i = declaredFunctions.values().iterator(); i.hasNext(); ) {
UserDefinedFunction func = (UserDefinedFunction) i.next();
if (func.getName().equals(name))
signatures.add(func.getSignature());
}
return signatures.iterator();
}
public Iterator localFunctions() {
return declaredFunctions.values().iterator();
}
/**
* Declare a local variable. This is called by variable binding expressions like
* "let" and "for".
*
* @param var
* @return
* @throws XPathException
*/
public LocalVariable declareVariableBinding(LocalVariable var) throws XPathException {
if(lastVar == null)
lastVar = var;
else {
lastVar.addAfter(var);
lastVar = var;
}
var.setStackPosition(variableStackSize);
return var;
}
/**
* Declare a global variable as by "declare variable".
*
* @param qname
* @param value
* @return
* @throws XPathException
*/
public Variable declareGlobalVariable(Variable var) throws XPathException {
globalVariables.put(var.getQName(), var);
var.setStackPosition(variableStackSize);
return var;
}
/**
* Declare a user-defined variable.
*
* The value argument is converted into an XPath value
* (@see XPathUtil#javaObjectToXPath(Object)).
*
* @param qname the qualified name of the new variable. Any namespaces should
* have been declared before.
* @param value a Java object, representing the fixed value of the variable
* @return the created Variable object
* @throws XPathException if the value cannot be converted into a known XPath value
* or the variable QName references an unknown namespace-prefix.
*/
public Variable declareVariable(String qname, Object value) throws XPathException {
QName qn = QName.parse(this, qname, null);
Variable var;
Module module = getModule(qn.getNamespaceURI());
if(module != null) {
var = module.declareVariable(qn, value);
return var;
}
Sequence val = XPathUtil.javaObjectToXPath(value, this);
var = (Variable)globalVariables.get(qn);
if(var == null) {
var = new Variable(qn);
globalVariables.put(qn, var);
}
//TODO : should we allow global variable *re*declaration ?
var.setValue(val);
return var;
}
/**
* Try to resolve a variable.
*
* @param qname the qualified name of the variable as string
* @return the declared Variable object
* @throws XPathException if the variable is unknown
*/
public Variable resolveVariable(String name) throws XPathException {
QName qn = QName.parse(this, name, null);
return resolveVariable(qn);
}
/**
* Try to resolve a variable.
*
* @param qname the qualified name of the variable
* @return the declared Variable object
* @throws XPathException if the variable is unknown
*/
public Variable resolveVariable(QName qname) throws XPathException {
Variable var;
// check if the variable is declared local
var = resolveLocalVariable(qname);
// check if the variable is declared in a module
if (var == null){
Module module = getModule(qname.getNamespaceURI());
if(module != null) {
var = module.resolveVariable(qname);
}
}
// check if the variable is declared global
if (var == null)
var = (Variable) globalVariables.get(qname);
if (var == null)
throw new XPathException("variable $" + qname + " is not bound");
return var;
}
private Variable resolveLocalVariable(QName qname) throws XPathException {
LocalVariable end = contextStack.isEmpty() ? null : (LocalVariable) contextStack.peek();
for(LocalVariable var = lastVar; var != null; var = var.before) {
if (var == end)
return null;
if(qname.equals(var.getQName()))
return var;
}
return null;
}
public boolean isVarDeclared(QName qname) {
Module module = getModule(qname.getNamespaceURI());
if(module != null) {
if (module.isVarDeclared(qname))
return true;
}
return globalVariables.get(qname) != null;
}
/**
* Turn on/off XPath 1.0 backwards compatibility.
*
* If turned on, comparison expressions will behave like
* in XPath 1.0, i.e. if any one of the operands is a number,
* the other operand will be cast to a double.
*
* @param backwardsCompatible
*/
public void setBackwardsCompatibility(boolean backwardsCompatible) {
this.backwardsCompatible = backwardsCompatible;
}
/**
* XPath 1.0 backwards compatibility turned on?
*
* In XPath 1.0 compatible mode, additional conversions
* will be applied to values if a numeric value is expected.
*
* @return
*/
public boolean isBackwardsCompatible() {
return this.backwardsCompatible;
}
/**
* Get the DBBroker instance used for the current query.
*
* The DBBroker is the main database access object, providing
* access to all internal database functions.
*
* @return
*/
public DBBroker getBroker() {
return broker;
}
public void setBroker(DBBroker broker) {
this.broker = broker;
}
/**
* Get the user which executes the current query.
*
* @return
*/
public User getUser() {
return broker.getUser();
}
/**
* Get the document builder currently used for creating
* temporary document fragments. A new document builder
* will be created on demand.
*
* @return
*/
public MemTreeBuilder getDocumentBuilder() {
if (builder == null) {
builder = new MemTreeBuilder(this);
builder.startDocument();
}
return builder;
}
/* Methods delegated to the watchdog */
public void proceed() throws TerminatedException {
proceed(null);
}
public void proceed(Expression expr) throws TerminatedException {
watchdog.proceed(expr);
}
public void proceed(Expression expr, MemTreeBuilder builder) throws TerminatedException {
watchdog.proceed(expr, builder);
}
public void recover() {
watchdog.reset();
builder = null;
}
public XQueryWatchDog getWatchDog() {
return watchdog;
}
protected void setWatchDog(XQueryWatchDog watchdog) {
this.watchdog = watchdog;
}
/**
* Push any document fragment created within the current
* execution context on the stack.
*/
public void pushDocumentContext() {
fragmentStack.push(builder);
builder = null;
}
public void popDocumentContext() {
if (!fragmentStack.isEmpty()) {
builder = (MemTreeBuilder) fragmentStack.pop();
}
}
/**
* Set the base URI for the evaluation context.
*
* This is the URI returned by the fn:base-uri()
* function.
*
* @param uri
*/
public void setBaseURI(String uri) {
setBaseURI(uri, false);
}
/**
* Set the base URI for the evaluation context.
*
* A base URI specified via the base-uri directive in the
* XQuery prolog overwrites any other setting.
*
* @param uri
* @param setInProlog
*/
public void setBaseURI(String uri, boolean setInProlog) {
if (baseURISetInProlog)
return;
if (uri == null)
baseURI = "";
baseURI = uri;
baseURISetInProlog = setInProlog;
}
/**
* Set the path to a base directory where modules should
* be loaded from. Relative module paths will be resolved against
* this directory. The property is usually set by the XQueryServlet or
* XQueryGenerator, but can also be specified manually.
*
* @param path
*/
public void setModuleLoadPath(String path) {
this.moduleLoadPath = path;
}
public String getModuleLoadPath() {
return moduleLoadPath;
}
/**
* Get the base URI of the evaluation context.
*
* This is the URI returned by the fn:base-uri() function.
*
* @return
*/
public String getBaseURI() {
return baseURI;
}
/**
* Set the current context position, i.e. the position
* of the currently processed item in the context sequence.
* This value is required by some expressions, e.g. fn:position().
*
* @param pos
*/
public void setContextPosition(int pos) {
contextPosition = pos;
}
/**
* Get the current context position, i.e. the position of
* the currently processed item in the context sequence.
*
* @return
*/
public int getContextPosition() {
return contextPosition;
}
/**
* Push all in-scope namespace declarations onto the stack.
*/
public void pushInScopeNamespaces() {
HashMap m = (HashMap) inScopeNamespaces.clone();
namespaceStack.push(inScopeNamespaces);
inScopeNamespaces = m;
}
public void popInScopeNamespaces() {
inScopeNamespaces = (HashMap) namespaceStack.pop();
}
public void pushNamespaceContext() {
HashMap m = (HashMap) namespaces.clone();
HashMap p = (HashMap) prefixes.clone();
namespaceStack.push(namespaces);
namespaceStack.push(prefixes);
namespaces = m;
prefixes = p;
}
public void popNamespaceContext() {
prefixes = (HashMap) namespaceStack.pop();
namespaces = (HashMap) namespaceStack.pop();
}
/**
* Returns the last variable on the local variable stack.
* The current variable context can be restored by passing
* the return value to {@link #popLocalVariables(LocalVariable)}.
*
* @return
*/
public LocalVariable markLocalVariables(boolean newContext) {
if (newContext)
contextStack.push(lastVar);
variableStackSize++;
return lastVar;
}
/**
* Restore the local variable stack to the position marked
* by variable var.
*
* @param var
*/
public void popLocalVariables(LocalVariable var) {
if(var != null) {
var.after = null;
if (!contextStack.isEmpty() && var == contextStack.peek()) {
contextStack.pop();
}
}
lastVar = var;
variableStackSize--;
}
/**
* Returns the current size of the stack. This is used to determine
* where a variable has been declared.
*
* @return
*/
public int getCurrentStackSize() {
return variableStackSize;
}
/**
* Import a module and make it available in this context. The prefix and
* location parameters are optional. If prefix is null, the default prefix specified
* by the module is used. If location is null, the module will be read from the
* namespace URI.
*
* @param namespaceURI
* @param prefix
* @param location
* @throws XPathException
*/
public void importModule(String namespaceURI, String prefix, String location)
throws XPathException {
Module module = getModule(namespaceURI);
if(module != null) {
LOG.debug("Module " + namespaceURI + " already present.");
} else {
if(location == null)
location = namespaceURI;
// is it a Java module?
if(location.startsWith(JAVA_URI_START)) {
location = location.substring(JAVA_URI_START.length());
module = loadBuiltInModule(namespaceURI, location);
} else {
Source source;
// Is the module source stored in the database?
if (location.startsWith(XMLDB_URI_START) || moduleLoadPath.startsWith(XMLDB_URI_START)) {
if (location.indexOf(':') < 0)
location = moduleLoadPath + '/' + location;
String path = location.substring(XMLDB_URI_START.length());
DocumentImpl sourceDoc = null;
try {
sourceDoc = broker.openDocument(path, Lock.READ_LOCK);
if (sourceDoc == null)
throw new XPathException("source for module " + location + " not found in database");
if (sourceDoc.getResourceType() != DocumentImpl.BINARY_FILE ||
!sourceDoc.getMimeType().equals("application/xquery"))
throw new XPathException("source for module " + location + " is not an XQuery or " +
"declares a wrong mime-type");
source = new DBSource(broker, (BinaryDocument) sourceDoc, true);
module = compileModule(namespaceURI, location, module, source);
} catch (PermissionDeniedException e) {
throw new XPathException("permission denied to read module source from " + location);
} finally {
if(sourceDoc != null)
sourceDoc.getUpdateLock().release(Lock.READ_LOCK);
}
// No. Load from file or URL
} else {
try {
source = SourceFactory.getSource(moduleLoadPath, location, true);
} catch (MalformedURLException e) {
throw new XPathException("source location for module " + namespaceURI + " should be a valid URL: " +
e.getMessage());
} catch (IOException e) {
throw new XPathException("source for module " + namespaceURI + " not found: " +
e.getMessage());
}
module = compileModule(namespaceURI, location, module, source);
}
}
}
if(prefix == null)
prefix = module.getDefaultPrefix();
declareNamespace(prefix, namespaceURI);
}
/**
* @param namespaceURI
* @param location
* @param module
* @param source
* @return
* @throws XPathException
*/
private Module compileModule(String namespaceURI, String location, Module module, Source source) throws XPathException {
LOG.debug("Loading module from " + location);
Reader reader;
try {
reader = source.getReader();
} catch (IOException e) {
throw new XPathException("IO exception while loading module " + namespaceURI, e);
}
XQueryContext modContext = new ModuleContext(this);
XQueryLexer lexer = new XQueryLexer(modContext, reader);
XQueryParser parser = new XQueryParser(lexer);
XQueryTreeParser astParser = new XQueryTreeParser(modContext);
try {
parser.xpath();
if (parser.foundErrors()) {
LOG.debug(parser.getErrorMessage());
throw new XPathException(
"error found while loading module from " + location + ": "
+ parser.getErrorMessage());
}
AST ast = parser.getAST();
PathExpr path = new PathExpr(modContext);
astParser.xpath(ast, path);
if (astParser.foundErrors()) {
throw new XPathException(
"error found while loading module from " + location + ": "
+ astParser.getErrorMessage(),
astParser.getLastException());
}
path.analyze(null, 0);
ExternalModule modExternal = astParser.getModule();
if(modExternal == null)
throw new XPathException("source at " + location + " is not a valid module");
if(!modExternal.getNamespaceURI().equals(namespaceURI))
throw new XPathException("namespace URI declared by module (" + modExternal.getNamespaceURI() +
") does not match namespace URI in import statement, which was: " + namespaceURI);
modules.put(modExternal.getNamespaceURI(), modExternal);
modExternal.setSource(source);
modExternal.setContext(modContext);
module = modExternal;
} catch (RecognitionException e) {
throw new XPathException(
"error found while loading module from " + location + ": " + e.getMessage(),
e.getLine(), e.getColumn());
} catch (TokenStreamException e) {
throw new XPathException(
"error found while loading module from " + location + ": " + e.getMessage(),
e);
} catch (XPathException e) {
e.prependMessage("Error while loading module " + location + ": ");
throw e;
} catch (Exception e) {
throw new XPathException("Internal error while loading module: " + location, e);
}
declareModuleVars(module);
return module;
}
private void declareModuleVars(Module module) {
String moduleNS = module.getNamespaceURI();
for (Iterator i = globalVariables.values().iterator(); i.hasNext(); ) {
Variable var = (Variable) i.next();
if (moduleNS.equals(var.getQName().getNamespaceURI())) {
module.declareVariable(var);
i.remove();
}
}
}
/**
* Add a forward reference to an undeclared function. Forward
* references will be resolved later.
*
* @param call
*/
public void addForwardReference(FunctionCall call) {
forwardReferences.push(call);
}
/**
* Resolve all forward references to previously undeclared functions.
*
* @throws XPathException
*/
public void resolveForwardReferences() throws XPathException {
while(!forwardReferences.empty()) {
FunctionCall call = (FunctionCall)forwardReferences.pop();
UserDefinedFunction func = resolveFunction(call.getQName(), call.getArgumentCount());
if(func == null)
throw new XPathException(call.getASTNode(),
"Call to undeclared function: " + call.getQName().toString());
call.resolveForwardReference(func);
}
}
/**
* Called by XUpdate to tell the query engine that it is running in
* exclusive mode, i.e. no other query is executed at the same time.
*
* @param exclusive
*/
public void setExclusiveMode(boolean exclusive) {
this.exclusive = exclusive;
}
public boolean inExclusiveMode() {
return exclusive;
}
public void addPragma(String qnameString, String contents) throws XPathException {
QName qn;
try {
qn = QName.parse(this, qnameString, defaultFunctionNamespace);
} catch (XPathException e) {
// unknown pragma: just ignore it
LOG.debug("Ignoring unknown pragma: " + qnameString);
return;
}
Pragma pragma = new Pragma(qn, contents);
if(pragmas == null)
pragmas = new ArrayList();
pragmas.add(pragma);
// check predefined pragmas
if (Pragma.PROFILE_QNAME.compareTo(qn) == 0) {
// configure profiling
profiler.configure(pragma);
} else if(Pragma.TIMEOUT_QNAME.compareTo(qn) == 0)
watchdog.setTimeoutFromPragma(pragma);
else if(Pragma.OUTPUT_SIZE_QNAME.compareTo(qn) == 0)
watchdog.setMaxNodesFromPragma(pragma);
}
public Pragma getPragma(QName qname) {
if(pragmas != null) {
Pragma pragma;
for(int i = 0; i < pragmas.size(); i++) {
pragma = (Pragma)pragmas.get(i);
if(qname.compareTo(pragma.getQName()) == 0)
return pragma;
}
}
return null;
}
/**
* Store the supplied data to a temporary document fragment.
*
* @param data
* @return
* @throws XPathException
*/
public DocumentImpl storeTemporaryDoc(org.exist.memtree.DocumentImpl doc) throws XPathException {
try {
DocumentImpl targetDoc = broker.storeTemporaryDoc(doc);
watchdog.addTemporaryFragment(targetDoc.getFileName());
LOG.debug("Stored: " + targetDoc.getDocId() + ": " + targetDoc.getName() +
": " + targetDoc.printTreeLevelOrder());
return targetDoc;
} catch (EXistException e) {
throw new XPathException(TEMP_STORE_ERROR, e);
} catch (PermissionDeniedException e) {
throw new XPathException(TEMP_STORE_ERROR, e);
} catch (LockException e) {
throw new XPathException(TEMP_STORE_ERROR, e);
}
}
/**
* Load the default prefix/namespace mappings table and set up
* internal functions.
*/
protected void loadDefaults(Configuration config) {
this.watchdog = new XQueryWatchDog(this);
namespaces = new HashMap();
prefixes = new HashMap();
/*
SymbolTable syms = broker.getSymbols();
String[] pfx = syms.defaultPrefixList();
namespaces = new HashMap(pfx.length);
prefixes = new HashMap(pfx.length);
String sym;
for (int i = 0; i < pfx.length; i++) {
sym = syms.getDefaultNamespace(pfx[i]);
namespaces.put(pfx[i], sym);
prefixes.put(sym, pfx[i]);
}
*/
try {
// default namespaces
namespaces.put("xml", XML_NS);
prefixes.put(XML_NS, "xml");
declareNamespace("xs", SCHEMA_NS);
declareNamespace("xdt", XPATH_DATATYPES_NS);
declareNamespace("local", XQUERY_LOCAL_NS);
declareNamespace("fn", Module.BUILTIN_FUNCTION_NS);
//*not* as standard NS
declareNamespace("exist", EXIST_NS);
} catch (XPathException e) {
//TODO : ignored because it should never happen
}
// load built-in modules
// these modules are loaded dynamically. It is not an error if the
// specified module class cannot be found in the classpath.
loadBuiltInModule(
Module.BUILTIN_FUNCTION_NS,
"org.exist.xquery.functions.ModuleImpl");
String modules[][] = (String[][]) config.getProperty("xquery.modules");
if ( modules != null ) {
for (int i = 0; i < modules.length; i++) {
// LOG.debug("Loading module " + modules[i][0]);
loadBuiltInModule(modules[i][0], modules[i][1]);
}
}
}
}
| src/org/exist/xquery/XQueryContext.java | /*
* eXist Open Source Native XML Database
* Copyright (C) 2001-03 Wolfgang M. Meier
* [email protected]
* http://exist.sourceforge.net
*
* 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.xquery;
import java.io.IOException;
import java.io.Reader;
import java.net.MalformedURLException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.TreeMap;
import org.apache.log4j.Logger;
import org.exist.EXistException;
import org.exist.collections.Collection;
import org.exist.dom.BinaryDocument;
import org.exist.dom.DocumentImpl;
import org.exist.dom.DocumentSet;
import org.exist.dom.NodeProxy;
import org.exist.dom.QName;
import org.exist.dom.SymbolTable;
import org.exist.memtree.MemTreeBuilder;
import org.exist.security.Permission;
import org.exist.security.PermissionDeniedException;
import org.exist.security.User;
import org.exist.source.DBSource;
import org.exist.source.Source;
import org.exist.source.SourceFactory;
import org.exist.storage.DBBroker;
import org.exist.storage.lock.Lock;
import org.exist.util.Collations;
import org.exist.util.Configuration;
import org.exist.util.LockException;
import org.exist.xquery.parser.XQueryLexer;
import org.exist.xquery.parser.XQueryParser;
import org.exist.xquery.parser.XQueryTreeParser;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.NodeValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceIterator;
import org.exist.xquery.value.Type;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import antlr.collections.AST;
/**
* The current XQuery execution context. Contains the static as well
* as the dynamic XQuery context components.
*
* @author Wolfgang Meier ([email protected])
*/
public class XQueryContext {
private static final String JAVA_URI_START = "java:";
private static final String XMLDB_URI_START = "xmldb:exist://";
public final static String XML_NS = "http://www.w3.org/XML/1998/namespace";
public final static String SCHEMA_NS = "http://www.w3.org/2001/XMLSchema";
public final static String SCHEMA_DATATYPES_NS =
"http://www.w3.org/2001/XMLSchema-datatypes";
public final static String SCHEMA_INSTANCE_NS =
"http://www.w3.org/2001/XMLSchema-instance";
public final static String XPATH_DATATYPES_NS =
"http://www.w3.org/2003/05/xpath-datatypes";
public final static String XQUERY_LOCAL_NS =
"http://www.w3.org/2003/08/xquery-local-functions";
public final static String EXIST_NS =
"http://exist.sourceforge.net/NS/exist";
private final static Logger LOG = Logger.getLogger(XQueryContext.class);
private static final String TEMP_STORE_ERROR = "Error occurred while storing temporary data";
private static final HashMap moduleClasses = new HashMap();
// Static namespace/prefix mappings
protected HashMap namespaces;
// Local in-scope namespace/prefix mappings in the current context
protected HashMap inScopeNamespaces = new HashMap();
// Static prefix/namespace mappings
protected HashMap prefixes;
// Local prefix/namespace mappings in the current context
protected HashMap inScopePrefixes = new HashMap();
// Local namespace stack
protected Stack namespaceStack = new Stack();
// Known user defined functions in the local module
protected TreeMap declaredFunctions = new TreeMap();
// Globally declared variables
protected TreeMap globalVariables = new TreeMap();
// The last element in the linked list of local in-scope variables
protected LocalVariable lastVar = null;
protected Stack contextStack = new Stack();
// The current size of the variable stack
protected int variableStackSize = 0;
// Unresolved references to user defined functions
protected Stack forwardReferences = new Stack();
// List of pragmas declared for this query
protected List pragmas = null;
/**
* the watchdog object assigned to this query
*
* @uml.property name="watchdog"
* @uml.associationEnd multiplicity="(1 1)"
*/
protected XQueryWatchDog watchdog;
/**
* Loaded modules.
*/
protected HashMap modules = new HashMap();
/**
* The set of statically known documents specified as
* an array of paths to documents and collections.
*/
protected String[] staticDocumentPaths = null;
/**
* The actual set of statically known documents. This
* will be generated on demand from staticDocumentPaths.
*/
protected DocumentSet staticDocuments = null;
/**
* The main database broker object providing access
* to storage and indexes. Every XQuery has its own
* DBBroker object.
*/
protected DBBroker broker;
protected String baseURI = "";
protected boolean baseURISetInProlog = false;
protected String moduleLoadPath = ".";
protected String defaultFunctionNamespace = Module.BUILTIN_FUNCTION_NS;
/**
* The default collation URI
*/
private String defaultCollation = Collations.CODEPOINT;
/**
* Default Collator. Will be null for the default unicode codepoint collation.
*/
private Collator defaultCollator = null;
/**
* Set to true to enable XPath 1.0
* backwards compatibility.
*/
private boolean backwardsCompatible = true;
/**
* Should whitespace inside node constructors be stripped?
*/
private boolean stripWhitespace = true;
/**
* The position of the currently processed item in the context
* sequence. This field has to be set on demand, for example,
* before calling the fn:position() function.
*/
private int contextPosition = 0;
/**
* The builder used for creating in-memory document
* fragments
*/
private MemTreeBuilder builder = null;
/**
* Stack for temporary document fragments
*/
private Stack fragmentStack = new Stack();
/**
* The root of the expression tree
*/
private Expression rootExpression;
/**
* Flag to indicate that the query should put an exclusive
* lock on all documents involved.
*
* TODO: No longer needed?
*/
private boolean exclusive = false;
/**
* Should all documents loaded by the query be locked?
* If set to true, it is the responsibility of the calling client
* code to unlock documents after the query has completed.
*/
private boolean lockDocumentsOnLoad = false;
/**
* Documents locked during the query.
*/
private DocumentSet lockedDocuments = null;
/**
* The profiler instance used by this context.
*/
private Profiler profiler = new Profiler();
//For holding XQuery Context variables from setXQueryContextVar() and getXQueryContextVar()
HashMap XQueryContextVars = new HashMap();
//set an XQuery Context variable; called by context:set-var()
public void setXQueryContextVar(String name, Object XQvar)
{
XQueryContextVars.put(name, XQvar);
}
//get an XQuery Context variable; called by context:get-var()
public Object getXQueryContextVar(String name)
{
return(XQueryContextVars.get(name));
}
protected XQueryContext() {
builder = new MemTreeBuilder(this);
builder.startDocument();
}
public XQueryContext(DBBroker broker) {
this();
this.broker = broker;
loadDefaults(broker.getConfiguration());
}
/**
* @return true if profiling is enabled for this context.
*/
public boolean isProfilingEnabled() {
return profiler.isEnabled();
}
public boolean isProfilingEnabled(int verbosity) {
return profiler.isEnabled() && profiler.verbosity() >= verbosity;
}
/**
* Returns the {@link Profiler} instance of this context
* if profiling is enabled.
*
* @return the profiler instance.
*/
public Profiler getProfiler() {
return profiler;
}
/**
* Called from the XQuery compiler to set the root expression
* for this context.
*
* @param expr
*/
public void setRootExpression(Expression expr) {
this.rootExpression = expr;
}
/**
* Returns the root expression of the XQuery associated with
* this context.
*
* @return
*/
public Expression getRootExpression() {
return rootExpression;
}
/**
* Declare a user-defined prefix/namespace mapping.
*
* eXist internally keeps a table containing all prefix/namespace
* mappings it found in documents, which have been previously
* stored into the database. These default mappings need not to be
* declared explicitely.
*
* @param prefix
* @param uri
*/
public void declareNamespace(String prefix, String uri) throws XPathException {
if (prefix == null)
prefix = "";
if(uri == null)
uri = "";
if (prefix.equals("xml") || prefix.equals("xmlns"))
throw new XPathException("err:XQST0070: Namespace predefined prefix: \"" + prefix + "\" is already bound");
if (uri.equals(XML_NS))
throw new XPathException("err:XQST0070: Namespace URI: \"" + uri + "\" must be bound to the 'xml' prefix");
final String prevURI = (String)namespaces.get(prefix);
//This prefix was not bound
if(prevURI == null ) {
//Bind it
if (uri.length() > 0) {
namespaces.put(prefix, uri);
prefixes.put(uri, prefix);
return;
}
//Nothing to bind
else {
//TODO : check the specs : unbinding an NS which is not already bound may be disallowed.
LOG.warn("trying to unbind unbound prefix: " + prefix);
}
}
else
//This prefix was bound
{
//Unbind it
if (uri.length() == 0) {
// if an empty namespace is specified,
// remove any existing mapping for this namespace
//TODO : improve, since XML_NS can't be unbound
prefixes.remove(uri);
namespaces.remove(prefix);
return;
}
//Forbids rebinding the *same* prefix in a *different* namespace in this *same* context
if (!uri.equals(prevURI))
throw new XPathException("err:XQST0033: Namespace prefix: \"" + prefix + "\" is already bound to a different uri");
}
}
public void declareNamespaces(Map namespaceMap) {
Map.Entry entry;
String prefix, uri;
for(Iterator i = namespaceMap.entrySet().iterator(); i.hasNext(); ) {
entry = (Map.Entry)i.next();
prefix = (String)entry.getKey();
uri = (String) entry.getValue();
if(prefix == null)
prefix = "";
if(uri == null)
uri = "";
namespaces.put(prefix, uri);
prefixes.put(uri, prefix);
}
}
/**
* Declare an in-scope namespace. This is called during query execution.
*
* @param prefix
* @param uri
*/
public void declareInScopeNamespace(String prefix, String uri) {
if (prefix == null || uri == null)
throw new IllegalArgumentException("null argument passed to declareNamespace");
if (inScopeNamespaces == null)
inScopeNamespaces = new HashMap();
inScopeNamespaces.put(prefix, uri);
}
/**
* Returns the current default function namespace.
*
* @return
*/
public String getDefaultFunctionNamespace() {
return defaultFunctionNamespace;
}
/**
* Set the default function namespace. By default, this
* points to the namespace for XPath built-in functions.
*
* @param uri
*/
public void setDefaultFunctionNamespace(String uri) {
defaultFunctionNamespace = uri;
}
/**
* Set the default collation to be used by all operators and functions on strings.
* Throws an exception if the collation is unknown or cannot be instantiated.
*
* @param uri
* @throws XPathException
*/
public void setDefaultCollation(String uri) throws XPathException {
if(uri.equals(Collations.CODEPOINT) || uri.equals(Collations.CODEPOINT_SHORT)) {
defaultCollation = Collations.CODEPOINT;
defaultCollator = null;
}
defaultCollator = Collations.getCollationFromURI(this, uri);
defaultCollation = uri;
}
public String getDefaultCollation() {
return defaultCollation;
}
public Collator getCollator(String uri) throws XPathException {
if(uri == null)
return defaultCollator;
return Collations.getCollationFromURI(this, uri);
}
public Collator getDefaultCollator() {
return defaultCollator;
}
/**
* Return the namespace URI mapped to the registered prefix
* or null if the prefix is not registered.
*
* @param prefix
* @return
*/
public String getURIForPrefix(String prefix) {
String ns = (String) namespaces.get(prefix);
if (ns == null)
// try in-scope namespace declarations
return inScopeNamespaces == null
? null
: (String) inScopeNamespaces.get(prefix);
else
return ns;
}
/**
* Return the prefix mapped to the registered URI or
* null if the URI is not registered.
*
* @param uri
* @return
*/
public String getPrefixForURI(String uri) {
String prefix = (String) prefixes.get(uri);
if (prefix == null)
return inScopePrefixes == null ? null : (String) inScopeNamespaces.get(uri);
else
return prefix;
}
/**
* Removes the namespace URI from the prefix/namespace
* mappings table.
*
* @param uri
*/
public void removeNamespace(String uri) {
prefixes.remove(uri);
for (Iterator i = namespaces.values().iterator(); i.hasNext();) {
if (((String) i.next()).equals(uri)) {
i.remove();
return;
}
}
inScopePrefixes.remove(uri);
if (inScopeNamespaces != null) {
for (Iterator i = inScopeNamespaces.values().iterator(); i.hasNext();) {
if (((String) i.next()).equals(uri)) {
i.remove();
return;
}
}
}
}
/**
* Clear all user-defined prefix/namespace mappings.
*/
public void clearNamespaces() {
namespaces.clear();
prefixes.clear();
if (inScopeNamespaces != null) {
inScopeNamespaces.clear();
inScopePrefixes.clear();
}
loadDefaults(broker.getConfiguration());
}
/**
* Set the set of statically known documents for the current
* execution context. These documents will be processed if
* no explicit document set has been set for the current expression
* with fn:doc() or fn:collection().
*
* @param docs
*/
public void setStaticallyKnownDocuments(String[] docs) {
staticDocumentPaths = docs;
}
public void setStaticallyKnownDocuments(DocumentSet set) {
staticDocuments = set;
}
/**
* Get the set of statically known documents.
*
* @return
*/
public DocumentSet getStaticallyKnownDocuments() throws XPathException {
if(staticDocuments != null)
// the document set has already been built, return it
return staticDocuments;
staticDocuments = new DocumentSet();
if(staticDocumentPaths == null)
// no path defined: return all documents in the db
broker.getAllDocuments(staticDocuments);
else {
DocumentImpl doc;
Collection collection;
for(int i = 0; i < staticDocumentPaths.length; i++) {
try {
doc = broker.openDocument(staticDocumentPaths[i], Lock.READ_LOCK);
if(doc != null) {
if(doc.getPermissions().validate(broker.getUser(), Permission.READ)) {
staticDocuments.add(doc);
}
doc.getUpdateLock().release(Lock.READ_LOCK);
} else {
collection = broker.getCollection(staticDocumentPaths[i]);
if(collection != null) {
LOG.debug("reading collection " + staticDocumentPaths[i]);
collection.allDocs(broker, staticDocuments, true, true);
}
}
} catch(PermissionDeniedException e) {
LOG.warn("Permission denied to read resource " + staticDocumentPaths[i] + ". Skipping it.");
}
}
}
return staticDocuments;
}
/**
* Should loaded documents be locked?
*
* @see #setLockDocumentsOnLoad(boolean)
*
* @return
*/
public boolean lockDocumentsOnLoad() {
return lockDocumentsOnLoad;
}
/**
* If lock is true, all documents loaded during query execution
* will be locked. This way, we avoid that query results become
* invalid before the entire result has been processed by the client
* code. All attempts to modify nodes which are part of the result
* set will be blocked.
*
* However, it is the client's responsibility to proper unlock
* all documents once processing is completed.
*
* @param lock
*/
public void setLockDocumentsOnLoad(boolean lock) {
lockDocumentsOnLoad = lock;
if(lock)
lockedDocuments = new DocumentSet();
}
/**
* Returns the set of documents that have been loaded and
* locked during query execution.
*
* @see #setLockDocumentsOnLoad(boolean)
*
* @return
*/
public DocumentSet getLockedDocuments() {
return lockedDocuments;
}
/**
* Release all locks on documents that have been locked
* during query execution.
*
*@see #setLockDocumentsOnLoad(boolean)
*/
public void releaseLockedDocuments() {
if(lockedDocuments != null)
lockedDocuments.unlock(false);
lockDocumentsOnLoad = false;
lockedDocuments = null;
}
/**
* Release all locks on documents not being referenced by the sequence.
* This is called after query execution has completed. Only locks on those
* documents contained in the final result set will be preserved. All other
* locks are released as they are no longer needed.
*
* @param seq
* @return
*/
public DocumentSet releaseUnusedDocuments(Sequence seq) {
if(lockedDocuments == null)
return null;
// determine the set of documents referenced by nodes in the sequence
DocumentSet usedDocs = new DocumentSet();
for(SequenceIterator i = seq.iterate(); i.hasNext(); ) {
Item next = i.nextItem();
if(Type.subTypeOf(next.getType(), Type.NODE)) {
NodeValue node = (NodeValue) next;
if(node.getImplementationType() == NodeValue.PERSISTENT_NODE) {
DocumentImpl doc = ((NodeProxy)node).getDocument();
if(!usedDocs.contains(doc.getDocId()))
usedDocs.add(doc, false);
}
}
}
DocumentSet remaining = new DocumentSet();
for(Iterator i = lockedDocuments.iterator(); i.hasNext(); ) {
DocumentImpl next = (DocumentImpl) i.next();
if(usedDocs.contains(next.getDocId())) {
remaining.add(next);
} else {
// LOG.debug("Releasing lock on " + next.getName());
next.getUpdateLock().release(Lock.READ_LOCK);
}
}
// LOG.debug("Locks remaining: " + remaining.getLength());
lockDocumentsOnLoad = false;
lockedDocuments = null;
return remaining;
}
/**
* Prepare this XQueryContext to be reused. This should be
* called when adding an XQuery to the cache.
*/
public void reset() {
builder = new MemTreeBuilder(this);
builder.startDocument();
staticDocumentPaths = null;
staticDocuments = null;
lastVar = null;
fragmentStack = new Stack();
watchdog.reset();
profiler.reset();
for(Iterator i = modules.values().iterator(); i.hasNext(); ) {
Module module = (Module)i.next();
module.reset();
}
}
/**
* Returns true if whitespace between constructed element nodes
* should be stripped by default.
*
* @return
*/
public boolean stripWhitespace() {
return stripWhitespace;
}
public void setStripWhitespace(boolean strip) {
this.stripWhitespace = strip;
}
/**
* Return an iterator over all built-in modules currently
* registered.
*
* @return
*/
public Iterator getModules() {
return modules.values().iterator();
}
/**
* Get the built-in module registered for the given namespace
* URI.
*
* @param namespaceURI
* @return
*/
public Module getModule(String namespaceURI) {
return (Module) modules.get(namespaceURI);
}
/**
* For compiled expressions: check if the source of any
* module imported by the current query has changed since
* compilation.
*
* @return
*/
public boolean checkModulesValid() {
for(Iterator i = modules.values().iterator(); i.hasNext(); ) {
Module module = (Module)i.next();
if(!module.isInternalModule()) {
if(!((ExternalModule)module).moduleIsValid()) {
LOG.debug("Module with URI " + module.getNamespaceURI() +
" has changed and needs to be reloaded");
return false;
}
}
}
return true;
}
/**
* Load a built-in module from the given class name and assign it to the
* namespace URI. The specified class should be a subclass of
* {@link Module}. The method will try to instantiate the class. If the
* class is not found or an exception is thrown, the method will silently
* fail. The namespace URI has to be equal to the namespace URI declared
* by the module class. Otherwise, the module is not loaded.
*
* @param namespaceURI
* @param moduleClass
*/
public Module loadBuiltInModule(String namespaceURI, String moduleClass) {
Module module = getModule(namespaceURI);
if (module != null) {
// LOG.debug("module " + namespaceURI + " is already present");
return module;
}
try {
Class mClass = (Class) moduleClasses.get(moduleClass);
if (mClass == null) {
mClass = Class.forName(moduleClass);
if (!(Module.class.isAssignableFrom(mClass))) {
LOG.warn(
"failed to load module. "
+ moduleClass
+ " is not an instance of org.exist.xquery.Module.");
return null;
}
moduleClasses.put(moduleClass, mClass);
}
module = (Module) mClass.newInstance();
if (!module.getNamespaceURI().equals(namespaceURI)) {
LOG.warn("the module declares a different namespace URI. Skipping...");
return null;
}
if (getPrefixForURI(module.getNamespaceURI()) == null
&& module.getDefaultPrefix().length() > 0)
declareNamespace(module.getDefaultPrefix(), module.getNamespaceURI());
modules.put(module.getNamespaceURI(), module);
//LOG.debug("module " + module.getNamespaceURI() + " loaded successfully.");
} catch (ClassNotFoundException e) {
//LOG.warn("module class " + moduleClass + " not found. Skipping...");
} catch (InstantiationException e) {
LOG.warn("error while instantiating module class " + moduleClass, e);
} catch (IllegalAccessException e) {
LOG.warn("error while instantiating module class " + moduleClass, e);
} catch (XPathException e) {
LOG.warn("error while instantiating module class " + moduleClass, e);
}
return module;
}
/**
* Declare a user-defined function. All user-defined functions are kept
* in a single hash map.
*
* @param function
* @throws XPathException
*/
public void declareFunction(UserDefinedFunction function) throws XPathException {
declaredFunctions.put(function.getSignature().getFunctionId(), function);
}
/**
* Resolve a user-defined function.
*
* @param name
* @return
* @throws XPathException
*/
public UserDefinedFunction resolveFunction(QName name, int argCount) throws XPathException {
FunctionId id = new FunctionId(name, argCount);
UserDefinedFunction func = (UserDefinedFunction) declaredFunctions.get(id);
return func;
}
public Iterator getSignaturesForFunction(QName name) {
ArrayList signatures = new ArrayList(2);
for (Iterator i = declaredFunctions.values().iterator(); i.hasNext(); ) {
UserDefinedFunction func = (UserDefinedFunction) i.next();
if (func.getName().equals(name))
signatures.add(func.getSignature());
}
return signatures.iterator();
}
public Iterator localFunctions() {
return declaredFunctions.values().iterator();
}
/**
* Declare a local variable. This is called by variable binding expressions like
* "let" and "for".
*
* @param var
* @return
* @throws XPathException
*/
public LocalVariable declareVariableBinding(LocalVariable var) throws XPathException {
if(lastVar == null)
lastVar = var;
else {
lastVar.addAfter(var);
lastVar = var;
}
var.setStackPosition(variableStackSize);
return var;
}
/**
* Declare a global variable as by "declare variable".
*
* @param qname
* @param value
* @return
* @throws XPathException
*/
public Variable declareGlobalVariable(Variable var) throws XPathException {
globalVariables.put(var.getQName(), var);
var.setStackPosition(variableStackSize);
return var;
}
/**
* Declare a user-defined variable.
*
* The value argument is converted into an XPath value
* (@see XPathUtil#javaObjectToXPath(Object)).
*
* @param qname the qualified name of the new variable. Any namespaces should
* have been declared before.
* @param value a Java object, representing the fixed value of the variable
* @return the created Variable object
* @throws XPathException if the value cannot be converted into a known XPath value
* or the variable QName references an unknown namespace-prefix.
*/
public Variable declareVariable(String qname, Object value) throws XPathException {
QName qn = QName.parse(this, qname, null);
Variable var;
Module module = getModule(qn.getNamespaceURI());
if(module != null) {
var = module.declareVariable(qn, value);
return var;
}
Sequence val = XPathUtil.javaObjectToXPath(value, this);
var = (Variable)globalVariables.get(qn);
if(var == null) {
var = new Variable(qn);
globalVariables.put(qn, var);
}
//TODO : should we allow global variable *re*declaration ?
var.setValue(val);
return var;
}
/**
* Try to resolve a variable.
*
* @param qname the qualified name of the variable as string
* @return the declared Variable object
* @throws XPathException if the variable is unknown
*/
public Variable resolveVariable(String name) throws XPathException {
QName qn = QName.parse(this, name, null);
return resolveVariable(qn);
}
/**
* Try to resolve a variable.
*
* @param qname the qualified name of the variable
* @return the declared Variable object
* @throws XPathException if the variable is unknown
*/
public Variable resolveVariable(QName qname) throws XPathException {
Variable var;
// check if the variable is declared local
var = resolveLocalVariable(qname);
// check if the variable is declared in a module
if (var == null){
Module module = getModule(qname.getNamespaceURI());
if(module != null) {
var = module.resolveVariable(qname);
}
}
// check if the variable is declared global
if (var == null)
var = (Variable) globalVariables.get(qname);
if (var == null)
throw new XPathException("variable $" + qname + " is not bound");
return var;
}
private Variable resolveLocalVariable(QName qname) throws XPathException {
LocalVariable end = contextStack.isEmpty() ? null : (LocalVariable) contextStack.peek();
for(LocalVariable var = lastVar; var != null; var = var.before) {
if (var == end)
return null;
if(qname.equals(var.getQName()))
return var;
}
return null;
}
public boolean isVarDeclared(QName qname) {
Module module = getModule(qname.getNamespaceURI());
if(module != null) {
if (module.isVarDeclared(qname))
return true;
}
return globalVariables.get(qname) != null;
}
/**
* Turn on/off XPath 1.0 backwards compatibility.
*
* If turned on, comparison expressions will behave like
* in XPath 1.0, i.e. if any one of the operands is a number,
* the other operand will be cast to a double.
*
* @param backwardsCompatible
*/
public void setBackwardsCompatibility(boolean backwardsCompatible) {
this.backwardsCompatible = backwardsCompatible;
}
/**
* XPath 1.0 backwards compatibility turned on?
*
* In XPath 1.0 compatible mode, additional conversions
* will be applied to values if a numeric value is expected.
*
* @return
*/
public boolean isBackwardsCompatible() {
return this.backwardsCompatible;
}
/**
* Get the DBBroker instance used for the current query.
*
* The DBBroker is the main database access object, providing
* access to all internal database functions.
*
* @return
*/
public DBBroker getBroker() {
return broker;
}
public void setBroker(DBBroker broker) {
this.broker = broker;
}
/**
* Get the user which executes the current query.
*
* @return
*/
public User getUser() {
return broker.getUser();
}
/**
* Get the document builder currently used for creating
* temporary document fragments. A new document builder
* will be created on demand.
*
* @return
*/
public MemTreeBuilder getDocumentBuilder() {
if (builder == null) {
builder = new MemTreeBuilder(this);
builder.startDocument();
}
return builder;
}
/* Methods delegated to the watchdog */
public void proceed() throws TerminatedException {
proceed(null);
}
public void proceed(Expression expr) throws TerminatedException {
watchdog.proceed(expr);
}
public void proceed(Expression expr, MemTreeBuilder builder) throws TerminatedException {
watchdog.proceed(expr, builder);
}
public void recover() {
watchdog.reset();
builder = null;
}
public XQueryWatchDog getWatchDog() {
return watchdog;
}
protected void setWatchDog(XQueryWatchDog watchdog) {
this.watchdog = watchdog;
}
/**
* Push any document fragment created within the current
* execution context on the stack.
*/
public void pushDocumentContext() {
fragmentStack.push(builder);
builder = null;
}
public void popDocumentContext() {
if (!fragmentStack.isEmpty()) {
builder = (MemTreeBuilder) fragmentStack.pop();
}
}
/**
* Set the base URI for the evaluation context.
*
* This is the URI returned by the fn:base-uri()
* function.
*
* @param uri
*/
public void setBaseURI(String uri) {
setBaseURI(uri, false);
}
/**
* Set the base URI for the evaluation context.
*
* A base URI specified via the base-uri directive in the
* XQuery prolog overwrites any other setting.
*
* @param uri
* @param setInProlog
*/
public void setBaseURI(String uri, boolean setInProlog) {
if (baseURISetInProlog)
return;
if (uri == null)
baseURI = "";
baseURI = uri;
baseURISetInProlog = setInProlog;
}
/**
* Set the path to a base directory where modules should
* be loaded from. Relative module paths will be resolved against
* this directory. The property is usually set by the XQueryServlet or
* XQueryGenerator, but can also be specified manually.
*
* @param path
*/
public void setModuleLoadPath(String path) {
this.moduleLoadPath = path;
}
public String getModuleLoadPath() {
return moduleLoadPath;
}
/**
* Get the base URI of the evaluation context.
*
* This is the URI returned by the fn:base-uri() function.
*
* @return
*/
public String getBaseURI() {
return baseURI;
}
/**
* Set the current context position, i.e. the position
* of the currently processed item in the context sequence.
* This value is required by some expressions, e.g. fn:position().
*
* @param pos
*/
public void setContextPosition(int pos) {
contextPosition = pos;
}
/**
* Get the current context position, i.e. the position of
* the currently processed item in the context sequence.
*
* @return
*/
public int getContextPosition() {
return contextPosition;
}
/**
* Push all in-scope namespace declarations onto the stack.
*/
public void pushInScopeNamespaces() {
HashMap m = (HashMap) inScopeNamespaces.clone();
namespaceStack.push(inScopeNamespaces);
inScopeNamespaces = m;
}
public void popInScopeNamespaces() {
inScopeNamespaces = (HashMap) namespaceStack.pop();
}
public void pushNamespaceContext() {
HashMap m = (HashMap) namespaces.clone();
HashMap p = (HashMap) prefixes.clone();
namespaceStack.push(namespaces);
namespaceStack.push(prefixes);
namespaces = m;
prefixes = p;
}
public void popNamespaceContext() {
prefixes = (HashMap) namespaceStack.pop();
namespaces = (HashMap) namespaceStack.pop();
}
/**
* Returns the last variable on the local variable stack.
* The current variable context can be restored by passing
* the return value to {@link #popLocalVariables(LocalVariable)}.
*
* @return
*/
public LocalVariable markLocalVariables(boolean newContext) {
if (newContext)
contextStack.push(lastVar);
variableStackSize++;
return lastVar;
}
/**
* Restore the local variable stack to the position marked
* by variable var.
*
* @param var
*/
public void popLocalVariables(LocalVariable var) {
if(var != null) {
var.after = null;
if (!contextStack.isEmpty() && var == contextStack.peek()) {
contextStack.pop();
}
}
lastVar = var;
variableStackSize--;
}
/**
* Returns the current size of the stack. This is used to determine
* where a variable has been declared.
*
* @return
*/
public int getCurrentStackSize() {
return variableStackSize;
}
/**
* Import a module and make it available in this context. The prefix and
* location parameters are optional. If prefix is null, the default prefix specified
* by the module is used. If location is null, the module will be read from the
* namespace URI.
*
* @param namespaceURI
* @param prefix
* @param location
* @throws XPathException
*/
public void importModule(String namespaceURI, String prefix, String location)
throws XPathException {
Module module = getModule(namespaceURI);
if(module != null) {
LOG.debug("Module " + namespaceURI + " already present.");
} else {
if(location == null)
location = namespaceURI;
// is it a Java module?
if(location.startsWith(JAVA_URI_START)) {
location = location.substring(JAVA_URI_START.length());
module = loadBuiltInModule(namespaceURI, location);
} else {
Source source;
// Is the module source stored in the database?
if (location.startsWith(XMLDB_URI_START) || moduleLoadPath.startsWith(XMLDB_URI_START)) {
if (location.indexOf(':') < 0)
location = moduleLoadPath + '/' + location;
String path = location.substring(XMLDB_URI_START.length());
DocumentImpl sourceDoc = null;
try {
sourceDoc = broker.openDocument(path, Lock.READ_LOCK);
if (sourceDoc == null)
throw new XPathException("source for module " + location + " not found in database");
if (sourceDoc.getResourceType() != DocumentImpl.BINARY_FILE ||
!sourceDoc.getMimeType().equals("application/xquery"))
throw new XPathException("source for module " + location + " is not an XQuery or " +
"declares a wrong mime-type");
source = new DBSource(broker, (BinaryDocument) sourceDoc, true);
module = compileModule(namespaceURI, location, module, source);
} catch (PermissionDeniedException e) {
throw new XPathException("permission denied to read module source from " + location);
} finally {
if(sourceDoc != null)
sourceDoc.getUpdateLock().release(Lock.READ_LOCK);
}
// No. Load from file or URL
} else {
try {
source = SourceFactory.getSource(moduleLoadPath, location, true);
} catch (MalformedURLException e) {
throw new XPathException("source location for module " + namespaceURI + " should be a valid URL: " +
e.getMessage());
} catch (IOException e) {
throw new XPathException("source for module " + namespaceURI + " not found: " +
e.getMessage());
}
module = compileModule(namespaceURI, location, module, source);
}
}
}
if(prefix == null)
prefix = module.getDefaultPrefix();
declareNamespace(prefix, namespaceURI);
}
/**
* @param namespaceURI
* @param location
* @param module
* @param source
* @return
* @throws XPathException
*/
private Module compileModule(String namespaceURI, String location, Module module, Source source) throws XPathException {
LOG.debug("Loading module from " + location);
Reader reader;
try {
reader = source.getReader();
} catch (IOException e) {
throw new XPathException("IO exception while loading module " + namespaceURI, e);
}
XQueryContext modContext = new ModuleContext(this);
XQueryLexer lexer = new XQueryLexer(modContext, reader);
XQueryParser parser = new XQueryParser(lexer);
XQueryTreeParser astParser = new XQueryTreeParser(modContext);
try {
parser.xpath();
if (parser.foundErrors()) {
LOG.debug(parser.getErrorMessage());
throw new XPathException(
"error found while loading module from " + location + ": "
+ parser.getErrorMessage());
}
AST ast = parser.getAST();
PathExpr path = new PathExpr(modContext);
astParser.xpath(ast, path);
if (astParser.foundErrors()) {
throw new XPathException(
"error found while loading module from " + location + ": "
+ astParser.getErrorMessage(),
astParser.getLastException());
}
path.analyze(null, 0);
ExternalModule modExternal = astParser.getModule();
if(modExternal == null)
throw new XPathException("source at " + location + " is not a valid module");
if(!modExternal.getNamespaceURI().equals(namespaceURI))
throw new XPathException("namespace URI declared by module (" + modExternal.getNamespaceURI() +
") does not match namespace URI in import statement, which was: " + namespaceURI);
modules.put(modExternal.getNamespaceURI(), modExternal);
modExternal.setSource(source);
modExternal.setContext(modContext);
module = modExternal;
} catch (RecognitionException e) {
throw new XPathException(
"error found while loading module from " + location + ": " + e.getMessage(),
e.getLine(), e.getColumn());
} catch (TokenStreamException e) {
throw new XPathException(
"error found while loading module from " + location + ": " + e.getMessage(),
e);
} catch (XPathException e) {
e.prependMessage("Error while loading module " + location + ": ");
throw e;
} catch (Exception e) {
throw new XPathException("Internal error while loading module: " + location, e);
}
declareModuleVars(module);
return module;
}
private void declareModuleVars(Module module) {
String moduleNS = module.getNamespaceURI();
for (Iterator i = globalVariables.values().iterator(); i.hasNext(); ) {
Variable var = (Variable) i.next();
if (moduleNS.equals(var.getQName().getNamespaceURI())) {
module.declareVariable(var);
i.remove();
}
}
}
/**
* Add a forward reference to an undeclared function. Forward
* references will be resolved later.
*
* @param call
*/
public void addForwardReference(FunctionCall call) {
forwardReferences.push(call);
}
/**
* Resolve all forward references to previously undeclared functions.
*
* @throws XPathException
*/
public void resolveForwardReferences() throws XPathException {
while(!forwardReferences.empty()) {
FunctionCall call = (FunctionCall)forwardReferences.pop();
UserDefinedFunction func = resolveFunction(call.getQName(), call.getArgumentCount());
if(func == null)
throw new XPathException(call.getASTNode(),
"Call to undeclared function: " + call.getQName().toString());
call.resolveForwardReference(func);
}
}
/**
* Called by XUpdate to tell the query engine that it is running in
* exclusive mode, i.e. no other query is executed at the same time.
*
* @param exclusive
*/
public void setExclusiveMode(boolean exclusive) {
this.exclusive = exclusive;
}
public boolean inExclusiveMode() {
return exclusive;
}
public void addPragma(String qnameString, String contents) throws XPathException {
QName qn;
try {
qn = QName.parse(this, qnameString, defaultFunctionNamespace);
} catch (XPathException e) {
// unknown pragma: just ignore it
LOG.debug("Ignoring unknown pragma: " + qnameString);
return;
}
Pragma pragma = new Pragma(qn, contents);
if(pragmas == null)
pragmas = new ArrayList();
pragmas.add(pragma);
// check predefined pragmas
if (Pragma.PROFILE_QNAME.compareTo(qn) == 0) {
// configure profiling
profiler.configure(pragma);
} else if(Pragma.TIMEOUT_QNAME.compareTo(qn) == 0)
watchdog.setTimeoutFromPragma(pragma);
else if(Pragma.OUTPUT_SIZE_QNAME.compareTo(qn) == 0)
watchdog.setMaxNodesFromPragma(pragma);
}
public Pragma getPragma(QName qname) {
if(pragmas != null) {
Pragma pragma;
for(int i = 0; i < pragmas.size(); i++) {
pragma = (Pragma)pragmas.get(i);
if(qname.compareTo(pragma.getQName()) == 0)
return pragma;
}
}
return null;
}
/**
* Store the supplied data to a temporary document fragment.
*
* @param data
* @return
* @throws XPathException
*/
public DocumentImpl storeTemporaryDoc(org.exist.memtree.DocumentImpl doc) throws XPathException {
try {
DocumentImpl targetDoc = broker.storeTemporaryDoc(doc);
watchdog.addTemporaryFragment(targetDoc.getFileName());
LOG.debug("Stored: " + targetDoc.getDocId() + ": " + targetDoc.getName() +
": " + targetDoc.printTreeLevelOrder());
return targetDoc;
} catch (EXistException e) {
throw new XPathException(TEMP_STORE_ERROR, e);
} catch (PermissionDeniedException e) {
throw new XPathException(TEMP_STORE_ERROR, e);
} catch (LockException e) {
throw new XPathException(TEMP_STORE_ERROR, e);
}
}
/**
* Load the default prefix/namespace mappings table and set up
* internal functions.
*/
protected void loadDefaults(Configuration config) {
this.watchdog = new XQueryWatchDog(this);
namespaces = new HashMap();
prefixes = new HashMap();
/*
SymbolTable syms = broker.getSymbols();
String[] pfx = syms.defaultPrefixList();
namespaces = new HashMap(pfx.length);
prefixes = new HashMap(pfx.length);
String sym;
for (int i = 0; i < pfx.length; i++) {
sym = syms.getDefaultNamespace(pfx[i]);
namespaces.put(pfx[i], sym);
prefixes.put(sym, pfx[i]);
}
*/
try {
// default namespaces
namespaces.put("xml", XML_NS);
prefixes.put(XML_NS, "xml");
declareNamespace("xs", SCHEMA_NS);
declareNamespace("xdt", XPATH_DATATYPES_NS);
declareNamespace("local", XQUERY_LOCAL_NS);
declareNamespace("fn", Module.BUILTIN_FUNCTION_NS);
//*not* as standard NS
declareNamespace("exist", EXIST_NS);
} catch (XPathException e) {
//TODO : ignored because it should never happen
}
// load built-in modules
// these modules are loaded dynamically. It is not an error if the
// specified module class cannot be found in the classpath.
loadBuiltInModule(
Module.BUILTIN_FUNCTION_NS,
"org.exist.xquery.functions.ModuleImpl");
String modules[][] = (String[][]) config.getProperty("xquery.modules");
if ( modules != null ) {
for (int i = 0; i < modules.length; i++) {
// LOG.debug("Loading module " + modules[i][0]);
loadBuiltInModule(modules[i][0], modules[i][1]);
}
}
}
}
| Improved namespaces declarations error messages.
svn path=/trunk/eXist-1.0/; revision=1951
| src/org/exist/xquery/XQueryContext.java | Improved namespaces declarations error messages. | <ide><path>rc/org/exist/xquery/XQueryContext.java
<ide> if(uri == null)
<ide> uri = "";
<ide> if (prefix.equals("xml") || prefix.equals("xmlns"))
<del> throw new XPathException("err:XQST0070: Namespace predefined prefix: \"" + prefix + "\" is already bound");
<add> throw new XPathException("err:XQST0070: Namespace predefined prefix '" + prefix + "' can not be bound");
<ide> if (uri.equals(XML_NS))
<del> throw new XPathException("err:XQST0070: Namespace URI: \"" + uri + "\" must be bound to the 'xml' prefix");
<add> throw new XPathException("err:XQST0070: Namespace URI '" + uri + "' must be bound to the 'xml' prefix");
<ide> final String prevURI = (String)namespaces.get(prefix);
<ide> //This prefix was not bound
<ide> if(prevURI == null ) {
<ide> //Nothing to bind
<ide> else {
<ide> //TODO : check the specs : unbinding an NS which is not already bound may be disallowed.
<del> LOG.warn("trying to unbind unbound prefix: " + prefix);
<add> LOG.warn("Unbinding unbound prefix '" + prefix + "'");
<ide> }
<ide> }
<ide> else
<ide> }
<ide> //Forbids rebinding the *same* prefix in a *different* namespace in this *same* context
<ide> if (!uri.equals(prevURI))
<del> throw new XPathException("err:XQST0033: Namespace prefix: \"" + prefix + "\" is already bound to a different uri");
<add> throw new XPathException("err:XQST0033: Namespace prefix '" + prefix + "' is already bound to a different uri '" + prevURI + "'");
<ide> }
<ide> }
<ide> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.