My solutions are below. Please check below points.
public class Program
{
public static void Main()
{
JobHostConfiguration config = new JobHostConfiguration();
config.NameResolver = new TimeResolver();
config.UseTimers();
JobHost host = new JobHost(config);
host.RunAndBlock();
}
private class TimeResolver : INameResolver
{
public string Resolve(string name)
{
string value = string.Empty;
switch (name)
{
case "TimerJob":
Console.WriteLine("Name Is TimerJob : " + name);
value = "00:00:10";
break;
case "TimerJobAlter":
Console.WriteLine("Name Is TimerJobAlter : " + name);
value = "00:00:20";
break;
}
return value;
}
}
//Runs once every 30 seconds
public static void TimerJob([TimerTrigger("%TimerJob%")] TimerInfo timer)
{
Console.WriteLine("Timer1 job fired!");
}
// Runs once every 60 seconds
public static void TimerJobAlter([TimerTrigger("%TimerJobAlter%")] TimerInfo timer)
{
Console.WriteLine("Timer2 job fired!");
}
}
Related
I have trouble using #UsingDataSet in my project.
Example in manual https://docs.jboss.org/author/display/ARQ/Persistence
doesn`t helps.
I have simple entity:
#Entity(name = "game")
#Table(name = "game_entity", schema = "graph")
#GenericGenerator(name="uuid2", strategy = "uuid2")
public class Game implements Serializable {
private static final long serialVersionUID = -4832711740307931146L;
private UUID id;
private String name;
#Id
#GeneratedValue(generator="uuid2")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
#NotNull
#Column(name = "name", length = 256, nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object value) {
if (!(value instanceof Game)) {
return false;
}
if (value == this) {
return true;
}
Game obj = (Game) value;
if (!obj.getId().equals(getId())) {
return false;
}
return true;
}
#Override
public int hashCode() {
int result = 29;
result += 29 * (getId() != null ? getId().hashCode() : 0);
result += 29*(getName() != null ? getName().hashCode() : 0);
return result;
}
}
And .yml file
game_entity:
- id : d5c58afd-7c99-41bb-ab0a-6357bfddfe14
name : Call of Duty
My test:
public class MyTest extends Arquillian {
#PersistenceContext(unitName = "spo")
private EntityManager em;
#Test
#UsingDataSet("datasets/gameDataSet.yml")
public void testAttribute() {
System.out.println("Hello world !");
}
#Deployment
public static WebArchive createArchive() {
WebArchive war = ShrinkWrap
.create(WebArchive.class, "myTest.war")
.addAsLibraries(
// blah-blah-blah
)
.addAsResource("my-persistence.xml", "META-INF/persistence.xml")
//.addAsResource("datasets/gameDataSet.yml", "datasets/gameDataSet.yml") // do I need to add this to archive ??
.addAsWebInfResource("META-INF/beans.xml", "beans.xml")
.setWebXML("web.xml")
;
return war;
}
}
When I run this test I getting 2 "strange" exeptions.
Sometimes:
Caused by: org.dbunit.dataset.NoSuchColumnException: game_entity.ID - (Non-uppercase input column: id) in ColumnNameToIndexes cache map. Note that the map's column names are NOT case sensitive.
But there are 2 columns in database! "id" and "name"
Sometimes, even more strange exception:
Caused by: org.postgresql.util.PSQLException: ERROR: relation "info_resource_attributes" does not exist
This is cross-table for another 2 entities, it exist in archive and myPersistence.xml but I dont use them in this test.
I use Wildfly 10 and Postgres 9.5. Without #UsingDataSet everything fine.
But I dont want programmaticaly hardcode data for tests like that:
Entity newEntityForTest = new Entity();
newEntityForTest.setA(...);
newEntityForTest.setB(...);
newEntityForTest.setC(...);
em.persist(newEntityForTest);
// testing ...
em.remove(newEntityForTest);
I need to read objects and save them in array. I did that on c# but can't figure out how to do that on actionscript.
c# example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestingWSDLLOad.ServiceReference2;
namespace TestingWSDLLOad
{
class Program
{
static void Main(string[] args)
{
ServiceReference2.Service1Client testas = new ServiceReference2.Service1Client();
SortedList<int, PlayListItem> playList = new SortedList<int, PlayListItem>();
int cc = 0;
foreach (var resultas in testas.GetPlayList(394570))
{
PlayListItem ss = new PlayListItem(resultas.Id, resultas.VideoId, resultas.Path);
playList.Add(cc, ss);
cc++;
}
Console.WriteLine(playList[0].Id);
Console.ReadKey();
}
}
public class PlayListItem
{
public int VideoId { get; private set; }
public string Path { get; private set; }
public int Id { get; private set; }
public PlayListItem(int id, int videoId, string path)
{
Id = id;
VideoId = videoId;
Path = path;
}
}
}
I know how to get a simple result from wsdl using actionscript, but don't know how to get objects with parameteres and save them.
Service has a method GetPlaylist(int value) which returns an array of objects (id, videoId, path). How to handle this and save them ?
Here is my as3:
package {
public class data extends CasparTemplate {
var flvControl:FLVPlayback;
var refreshTimer:Timer;
var videoList:Array;
var videoNew:Array;
var videoMaxIds:Array;
var videoNewMaxIds:Array;
var videoIndex:uint;
var videoIdFrom:uint;
var loopAtEnd:Boolean;
var _playListItems:Array;
var _playList:PlayListItem;
var gotNewPlaylist:Boolean;
var webService:WebService;
var serviceOperation:AbstractOperation;
public function data()
{
_playListItems = new Array();
flvControl = new FLVPlayback();
videoNew = new Array();
videoNewMaxIds = new Array();
videoIndex = 0;
videoIdFrom = videoMaxIds[videoIndex];
loopAtEnd = true;
gotNewPlaylist = false;
refreshTimer = new Timer(20000);
refreshTimer.addEventListener(TimerEvent.TIMER, getNewPlaylist);
refreshTimer.start();
flvControl.addEventListener(VideoEvent.COMPLETE, completeHandler);
flvControl.addEventListener(VideoEvent.STATE_CHANGE, vidState);
flvControl.setSize(720, 576);
flvControl.visible = true;
//addChild(flvControl);
var url:String = "http://xxx/yyy.svc?wsdl";
webService = new WebService();
webService.loadWSDL(url);
webService.addEventListener(LoadEvent.LOAD, BuildServiceRequest);
}
function BuildServiceRequest(evt:LoadEvent):void
{
webService.removeEventListener(LoadEvent.LOAD, BuildServiceRequest);
//serviceOperation.addEventListener(ResultEvent.RESULT, displayResult);
for (var resultas in webService.getOperation("GetPlaylist(394575)"))
{
trace(resultas.Id);
}
//serviceOperation = webService.getOperation("GetPlaylist");
//serviceOperation.arguments[{videoId: "394575"}];
}
private function displayResult(e:ResultEvent):void
{
trace("sss");
}
// Handle the video completion (load the next video)
function completeHandler(event:VideoEvent):void
{
if (gotNewPlaylist)
{
videoList = videoNew;
videoMaxIds = videoNewMaxIds;
videoNew = null;
videoNewMaxIds = null;
gotNewPlaylist = false;
videoIndex = 0;
} else
videoIndex++;
nextVideo();
}
private function vidState(e:VideoEvent):void {
var flvPlayer:FLVPlayback = e.currentTarget as FLVPlayback;
if (flvPlayer.state==VideoState.CONNECTION_ERROR) {
trace("FLVPlayer Connection Error! -> path : "+flvPlayer.source);
videoIndex++;
nextVideo();
} else if (flvPlayer.state==VideoState.DISCONNECTED) {
videoIndex++;
nextVideo();
}
}
function nextVideo():void
{
trace("Video List:"+videoList.toString());
if( videoIndex == videoList.length ){
if( loopAtEnd )
{
videoIndex = 0;
} else { return; }
}
flvControl.source = videoList[videoIndex];
if (videoIdFrom < videoMaxIds[videoIndex])
videoIdFrom = videoMaxIds[videoIndex];
trace(videoIdFrom);
}
}
}
internal class PlayListItem
{
private var _videoId:int;
private var _path:String;
private var _id:int;
public function get VideoId():int { return _videoId; }
public function get Path():String { return _path; }
public function get Id():int { return _id; }
public function set VideoId(setValue:int):void { _videoId = setValue };
public function set Path(setValue:String):void { _path = setValue };
public function set Id(setValue:int):void { _id = setValue };
public function PlayListItem(id:int, videoId:int, path:String)
{
_videoId = videoId;
_id = id;
_path = path;
}// end function
}
I think you were on the right track with your commented-out code. Be aware that the getOperation() will return an AbstractOperation, which in my mind is simply a pointer to the remote function. You can set arguments on the object, or simply pass the arguments when you call send(). I know some people have had issues with the argument property approach, so simply passing your arguments in the send function may be the smart way to go.
The following replace BuildServiceRequest and displayResult
private function BuildServiceRequest(evt:LoadEvent):void {
webService.removeEventListener(LoadEvent.LOAD, BuildServiceRequest);
serviceOperation.addEventListener(ResultEvent.RESULT, displayResult);
serviceOperation = webService.getOperation("GetPlaylist");
serviceOperation.send(394575);
}
private function displayResult(e:ResultEvent):void {
// Store the token as our array.
_playListItems = e.token;
var msg:String;
// Loop through the array
for each (var entry:Object in _playListItems) {
msg = "";
// For every key:value pair, compose a message to trace
for (var key:String in entry) {
msg += key + ":" + entry[key] + " ";
}
trace(msg);
}
}
I have several Build Definitions in RTC/Jazz and i use a variable to set out DB-Release in various Build Definitions
Build-Lib
Build-Server-App
Build-Run-Test-Server
Build-Client-App
Build-Run-Test-Client
and in all Definitions i use the Property DB_SCHEMA,
DB_SCHEMA = 8.1
once we update our DB and use a new Schema i have to set the Build Property up to
DB_SCHEMA = 8.2
now i must update all Build-Definitions... and if i forget one or i misspell something, then my boss gets mad at me - joking, but honestly, i don't want to make mistakes
--> how can i define a global Property that can be used in all Build-Definitions?
I don't see any global property in the help page, so you might consider developing a program:
using the RTC Java API
for each build definition, setting the property to the expected value (as in this thread)
IBuildDefinition definition = (IBuildDefinition) buildDefinition.getWorkingCopy();
definition.setProperty("propertyName","");
definition = buildClient.save(definition, monitor);
Ok VonC here is my solution:
one Part is an RTC-Adapter which handles Connections from and to the RTC base:
(it provides further getter/setters wich are not relevant for this solution - i purged them)
RTC-Adapter
public class RtcAdapter {
//yes i know - having hardcoded user/pass is bad, ignore this - image it's in a property file or set by a popup dialog
private static final String repositoryURI = "https://xxxxxxxxxxxx/ccm";
private static final String userId = "xxxxxxxxxxx";
private static final String password = "xxxxxxxxxx";
private static final String projectAreaName = "xxxxxxxxxx";
private ITeamRepository teamRepository = null;
private IProgressMonitor monitor = new NullProgressMonitor();
private IProjectArea projectArea = null;
private ITeamBuildClient buildClient = null;
//i'm implementing a singleton class - you can argue with mie if it's a good approach
private static final RtcAdapter inst = new RtcAdapter();
private RtcAdapter(){
super();
}
public ITeamRepository getTeamRepository() {
return teamRepository;
}
public IProgressMonitor getMonitor() {
return monitor;
}
public IProjectArea getProjctArea(){
return projectArea;
}
public ITeamBuildClient getBuildClient(){
return buildClient;
}
private void setTeamRepository(ITeamRepository teamRepositoryIn) {
teamRepository = teamRepositoryIn;
}
/**
*
* #param repositoryURI
* #param userId
* #param password
* #param monitor
* #return
* #throws TeamRepositoryException
*/
private ITeamRepository login(String repositoryURI, String userId,String password, IProgressMonitor monitor) throws TeamRepositoryException {
ITeamRepository teamRepository = TeamPlatform.getTeamRepositoryService().getTeamRepository(repositoryURI);
teamRepository.registerLoginHandler(new LoginHandler(userId, password));
teamRepository.login(monitor);
return teamRepository;
}
/**
* LoginHandler required by login function
*
*/
private static class LoginHandler implements ILoginHandler, ILoginInfo {
private String fUserId;
private String fPassword;
private LoginHandler(String userId, String password) {
fUserId = userId;
fPassword = password;
}
public String getUserId() {
return fUserId;
}
public String getPassword() {
return fPassword;
}
public ILoginInfo challenge(ITeamRepository repository) {
return this;
}
}
public static RtcAdapter inst() {
return inst;
}
public boolean connect() {
TeamPlatform.startup();
System.out.println("Team Platform Startup");
try {
IProgressMonitor monitor = new NullProgressMonitor();
setTeamRepository(login(repositoryURI, userId, password, monitor));
System.out.println("Logged in");
IProcessClientService processClient= (IProcessClientService) getTeamRepository().getClientLibrary(IProcessClientService.class);
URI uri= URI.create(projectAreaName.replaceAll(" ", "%20"));
projectArea = (IProjectArea) processClient.findProcessArea(uri, null, RtcAdapter.inst().getMonitor() );
buildClient = (ITeamBuildClient) getTeamRepository().getClientLibrary(ITeamBuildClient.class);
System.out.println("projet area = "+projectArea.getName() );
} catch (TeamRepositoryException e) {
System.out.println("TeamRepositoryException : " + e.getMessage());
e.printStackTrace();
return false;
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
public void disconnect(){
System.out.println("Logged out");
TeamPlatform.shutdown();
}
}
the other part is the working Class, i called it BuildDefinitionHelper (what a great name, haha)
BuildDefinitionHelper
public class BuildDefinitionHelper {
/**
* #param args
*/
public static void main(String[] args) {
new BuildDefinitionHelper().startUp(); //not-so-nice startup, but i don't mind
}
private final String[] adaPublishDefinitionList = new String[]{
"publish ada develop-40",
"publish ada develop-40 nightly",
"publish ada develop-54",
"publish ada develop-54 nightly",
"publish ada develop-56",
"publish ada develop-56 nightly",
"publish ada develop-58",
"publish ada develop-58 nightly",
};
private final String BUILD_NR = "BUILD_NR";
private final String MAJOR = "MAJOR";
private final String MINOR = "MINOR";
private void startUp() {
final int major = 57;
final int minor = 11;
final int build = 1;
//connect
if (RtcAdapter.inst().connect() ){
//getting required resources - a singleton is helpful here (look above)
IProgressMonitor pMon = RtcAdapter.inst().getMonitor();
ITeamBuildClient buildClient = RtcAdapter.inst().getBuildClient();
try {
for (String adaPublish: adaPublishDefinitionList ){
//get build definition
IBuildDefinition workingCopy = getBuildDefinition(adaPublish, buildClient, pMon);
//seting properties
String propMajor = getFormattededInteger(major);
String propMinor = getFormattededInteger(minor);
String propBuild = getFormattededInteger(build);
setBuildProperty(MAJOR, propMajor, workingCopy);
setBuildProperty(MINOR, propMinor, workingCopy);
setBuildProperty(BUILD_NR, propBuild, workingCopy);
//store changes
saveBuildDefinition(workingCopy, buildClient, pMon);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (TeamRepositoryException e) {
e.printStackTrace();
}
//at the end: disconnect
RtcAdapter.inst().disconnect();
}
}
private void saveBuildDefinition(IBuildDefinition definition, ITeamBuildClient buildClient, IProgressMonitor progressMonitor) throws TeamBuildDuplicateItemException, IllegalArgumentException, TeamRepositoryException {
buildClient.save(definition, progressMonitor);
}
private String getFormattededInteger(int value) {
if (value >= 0 && value <= 9){
return "00"+value;
}
if (value >= 10 && value <= 99){
return "0"+value;
}
return ""+value;
}
private IBuildDefinition getBuildDefinition(String buildDefinitionName, ITeamBuildClient buildClient, IProgressMonitor progressMonitor) throws IllegalArgumentException, TeamRepositoryException {
IBuildDefinition buildDefinition = buildClient.getBuildDefinition(buildDefinitionName, progressMonitor );
IBuildDefinition definition = (IBuildDefinition) buildDefinition.getWorkingCopy();
return definition;
}
private void setBuildProperty(String propertyName, String propertyValue, IBuildDefinition definition ) throws TeamBuildDuplicateItemException, IllegalArgumentException, TeamRepositoryException {
definition.setProperty(propertyName,propertyValue);
System.out.println("set "+propertyName+" to "+ propertyValue+" in Build Definition "+definition.getId() );
}
private void printBuildDefinition(String[] buildDefinitionList, ITeamBuildClient buildClient, IProgressMonitor progressMonitor) throws IllegalArgumentException, TeamRepositoryException {
for (String buildDefinitionName: buildDefinitionList ){
IBuildDefinition buildDefinition = buildClient.getBuildDefinition(buildDefinitionName, progressMonitor );
IBuildDefinition definition = (IBuildDefinition) buildDefinition.getWorkingCopy();
System.out.println("name = "+buildDefinitionName+" definition = "+definition);
}
}
}
I am just starting with Akka and have created a test application. In it I create a bunch of actors who create a scheduler to generate a heartbeat event. Upon another type of event, I cancel the scheduler with heartbeat.cancel();, but I'd like to restart it when another event occurs. If I recreate the scheduler I see that the memory consumption increases continuously.
The question then would be either how do I resume the scheduler or how do I dispose the scheduler properly.
This is the code for that Actor
public class Device extends UntypedActor {
enum CommunicationStatus{
OK,
FAIL,
UNKNOWN
}
private static class Heartbeat {
}
public final String deviceId;
private CommunicationStatus commStatus;
private Cancellable heartBeatScheduler;
public Device(String Id)
{
deviceId = Id;
commStatus = CommunicationStatus.UNKNOWN;
}
#Override
public void preStart() {
getContext().system().eventStream().subscribe(getSelf(), DeviceCommunicationStatusUpdated.class);
startHeartbeat();
}
#Override
public void postStop() {
stopHeartBeat();
}
private void startHeartbeat() {
LoggingAdapter log = Logging.getLogger(getContext().system(), this);
log.info("Starting heartbeat");
heartBeatScheduler = getContext().system().scheduler().
schedule(Duration.Zero(),
Duration.create(1, TimeUnit.SECONDS),
getContext().self(),
new Heartbeat(),
getContext().system().dispatcher(),
ActorRef.noSender());
}
private void stopHeartBeat() {
if(!heartBeatScheduler.isCancelled()) {
LoggingAdapter log = Logging.getLogger(getContext().system(), this);
log.info("Stopping heartbeat");
heartBeatScheduler.cancel();
}
}
public String getDeviceId() {
return deviceId;
}
public CommunicationStatus getCommunicationStatus(){
return commStatus;
}
#Override
public void onReceive(Object message) throws Exception {
LoggingAdapter log = Logging.getLogger(getContext().system(), this);
if(message instanceof Heartbeat){
log.info("Pum, pum");
}
else if (message instanceof DeviceCommunicationStatusUpdated){
DeviceCommunicationStatusUpdated event = (DeviceCommunicationStatusUpdated) message;
if(event.deviceId == this.deviceId){
log.info("Received communication status update. '{}' is now {}", deviceId, event.state);
this.commStatus =
event.state == DeviceCommunicationStatusUpdated.State.OK ?
CommunicationStatus.OK : CommunicationStatus.FAIL;
if(commStatus == CommunicationStatus.OK && heartBeatScheduler.isCancelled()){
startHeartbeat();
}
else {
stopHeartBeat();
}
}
}
else unhandled(message);
}
}
Finally there is no leak, it's just that I'm new to Java and was impatient with the garbage collection. In any case, I would like to know about the resetting / restarting of a scheduler.
I have tried for days but I couldn't reach any successful result. I need to post images with their information (s.t. created user name).
This is my method;
[HttpPost]
public Task<HttpResponseMessage> PostFile(string createdByName)
{
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = System.Configuration.ConfigurationSettings.AppSettings["TempUploadDir"];
var provider = new MultipartFormDataStreamProvider(root);
var task = request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(o =>
{
AddImages(provider.BodyPartFileNames);
string file1 = provider.BodyPartFileNames.First().Value;
// this is the file name on the server where the file was saved
return new HttpResponseMessage()
{
Content = new StringContent("File uploaded.")
};
}
);
return task;
}
And this my TypeFormatterClass which is added global.asax
public class MultiFormDataMediaTypeFormatter : FormUrlEncodedMediaTypeFormatter
{
public MultiFormDataMediaTypeFormatter()
: base()
{
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
}
protected override bool CanReadType(Type type)
{
return true;
}
protected override bool CanWriteType(Type type)
{
return false;
}
protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
{
var contents = formatterContext.Request.Content.ReadAsMultipartAsync().Result;
return Task.Factory.StartNew<object>(() =>
{
return new MultiFormKeyValueModel(contents);
});
}
class MultiFormKeyValueModel : IKeyValueModel
{
IEnumerable<HttpContent> _contents;
public MultiFormKeyValueModel(IEnumerable<HttpContent> contents)
{
_contents = contents;
}
public IEnumerable<string> Keys
{
get
{
return _contents.Cast<string>();
}
}
public bool TryGetValue(string key, out object value)
{
value = _contents.FirstDispositionNameOrDefault(key).ReadAsStringAsync().Result;
return true;
}
}
}
When I post images and "createdByName" I can reach images but I couldn't parameters. How can I do this?
Thank you.
To get your createdByName field, inside your ContinueWith :
var parts = o.Result;
HttpContent namePart = parts.FirstDispositionNameOrDefault("createdByName");
if (namePart == null)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
string name = namePart.ReadAsStringAsync().Result;
For a more detailed example, see :
http://www.asp.net/web-api/overview/working-with-http/html-forms-and-multipart-mime#multipartmime