The wife and I braved the afternoon drizzle yesterday to visit the sales gallery of THE INTERLACE, located at the former Gillman Heights site.
THE INTERLACE, scheduled for TOP by March 2015, is a 1,040-unit development built on 870,000 sq ft of elevated land. It comprises 31 apartment blocks, stacked in a hexagonal arrangement to form eight large-scale courtyards. The interlocking blocks resemble a "vertical village" with cascading sky gardens and both private and public roof terraces. Each apartment block (or "Superlevel") is 6-storey high, so the highest units are either on the 18th or 24th storey, depending on the stack. This unique design is the brainchild of Ole Scheeren from the Office of Metropolitan Architecture (OMA), who also designed the China Central Television Station (CCTV) headquarters in Beijing and the Prada Epicenters in NYC and L.A.
One cannot argue about the central location of THE INTERLACE. It is just a 5-minutes drive to Vivocity & Sentosa (think I.R.), 10-minutes drive to the CBD and 15-minutes to Orchard Road. The development is accessible via the AYE and West Coast Highway, while the uncompleted Labrador Park MRT station is about a 10-minutes walk away. We were told that there will also be a feeder bus service to Vivocity, which provide an added dimension of convenience.
In addition, there are also some retail shop units for sale within the development itself. A total of 1,132 underground carpark (inclusive of 10 handicap) lots are available, and owners of the Townhouse units will get 2 carpark lots each.
THE INTERLACE was soft launched in Sep 2009, with 233 out of the 360 units sold within the first week. The project was then opened for public booking in Oct 2009, and the sales gallery was subsequently moved from the previous location at River Valley to the current site last weekend. We understand from the marketing agent that less than 70% of the units were sold so far, which implies that sales have been sluggish after the soft launch euphoria.
True to our previous post on this project, there is no showflat available for viewing – what you get is a large model of the development showing the block layouts and the facilities available, as well as model of the 3, 4 and 4-MG (Multi Generation, which is basically a 3-bedroom + studio unit) apartments. You also get to see the type of building materials that will be used for the apartment flooring, walls and wardrobes, but you have to imagine how all these will fit together for the final look. We were told that there will eventually be showflats available sometime during 2Q 2010. The developers felt that THE INTERLACE will sell by their names alone, given that both CapitaLand and HPL are "reputed" for quality high end projects like Four Seasons Park, Nassim Jade etc. As such, there is no real need for showflats. But being the conventionalist, we both feel that a showflat is still the best way for potential buyers to visualize how his apartment will/can look like. And going by how "fast" units are flying off the shelves, we may not be the only ones that feel that way.
The units for the first phase are mainly in the blocks facing the AYE (Blocks 194, 196, 202, 204), and the penthouses (Block 220, 222). We were told that there is a 40m ingress between Blocks 194 and 196 from the AYE, and a 60m ingress for Blocks 202 and 204. So these should provide owners with some insulation from the traffic noise. The 18 penthouses launched are located on the fourth "Superlevel" (i.e. between the 19th and 24th floors), and are a mix of single level units and duplexes. This provides a whole new meaning to our understanding of "Penthouse", which is a unit on the highest level of any apartment block. Then again, when you have developers hawking "baby penthouses" of less than 1,300 sq ft, anything is possible these days.
• Theatre Plaza – where the clubhouse, gym, theaterette, billards/karaoke/function rooms are.
• Water Park – where the 50m lap and different "themed" swimming pools are.
• Play Hills – outdoor exercise and play area.
• Spa Valley – spa & massage pools, Jacuzzi and steam rooms.
• Theatre Plaza – outdoor extension to the clubhouse's theaterette, for performance or outdoor movie screenings etc.
• Bamboo Garden – supposedly where a bamboo forest and rock gardens reside.
• Lotus Pond – supposedly 40m across.. more like a lake!
• Waterfall Terrace – where the 3 tennis courts, multi-purpose court, another large swimming pool and party pavilions are found.
The developer has created two viewing galleries on the 18th floor of an existing block to showcase the type of view you will get with some of the "good facing" units. We must say that the view offered by the South-facing units (assuming unblocked) is quite impressive – you get both the sea view beyond Labrador Park and greenery view around Hort Park/Southern Ridges. However, you have to be on the 13th floor or above to enjoy this view, else you be blocked by the tree lines. And before you go rushing down to the sales gallery with that cheque book, the units with this facing are not launched for sale yet! The North-facing units will get the City/Flyer view, which will come in handy for watching the fireworks display during National Day etc. However, you will also be facing the AYE and some of the industrial building/factory rooftops along Lower Delta, which may not be all that appealing.
• The location – proximity to CBD, Orchard, One North, Fusion & Biopolis. Investors can expect good rental potential.
• The 4-MG unit layout looks interesting – this is one of the few projects that offer such a layout. The fully contained studio unit within the apartment, with its own kitchen and living/dining area, is ideal for people living with extended family (in-laws, grandparents) or have frequent visitors that stay over.
• The living room has homogenous tiles flooring – this is somewhat disappointing for a project from two "high end quality" developers.
• We may be wrong, but we suspect some of the lower floor, inward facing units will suffer from insufficient natural lighting. So be prepared to switch on the lights even during daytime.
• The layout of the blocks and units, while unique, do come across as "confusing", so good luck to first time visitors trying to locate your unit. You may also have problem finding your apartment after a few drinks.
• The wife has noticed that the bathrooms/toilets of most units are located in the centre of the apartment (extremely bad Feng Shui!) and without natural ventilations (windows). Experience has taught us that the artificial ventilators cannot expel odors as efficiently in a fully wall-enclosed toilet, so you are likely to get some "interesting smell" coming out from that toilet after awhile.
• We cannot locate any primary school within 1-km of THE INTERLACE.
• And finally, the price. THE INTERLACE is currently selling at between $850 to $1,150 psf. So you can expect to pay an average price of about $1,000 psf for a typical unit. We feel that this is somewhat at the higher end for current 99-years projects. This is especially when you have to put your money down mostly by faith, given the atypical design (which can either turned out to be superb or an absolute disaster) and lack of visual representation on what you will actually get.
In summary, we feel that the judgment is still out on THE INTERLACE. We will probably be able to form a better opinion about this project once the showflats are up and the prices for the "better facing" units are available. Thus, expect another update on this development in a couple of months' time.
And if you are still keen to visit the sales gallery meantime, do remember to bring along an umbrella in case it rains – the sales gallery (at the former clubhouse of Gillman Heights) is situated quite a distance from the carpark area, with no sheltered walkway in between.
No Comment to " THE INTERLACE (1st Preview) "


The Doctrine-Keeper is a Ranalon guardian who enforces proper practice of Ranalon culture. Found deep in the Ranalon Den, this being's beliefs are almost infectious.
Found in the northwest most room of the cave system. 15 min spawn timer. There is a timer on how often this mob will drop full loot for an individual, its over an hour but less than three. While you CAN kill him every 15 minutes you only get the possibility of a scroll dropping every so often (1-3 hours).
Druids are vigilantes. They have no place in civilized society.
The oceans are pure. And thus Onoyos is the most pure god.
Dreva is supposed to be the god of Balance. Laughable, really, given how poorly Dreva treats the Ranlon race.
Respect the sea and reap its bounties!
You've been indoctrinated into the culture of the ranalon race.This is a permanent curse; you must defeat the Ranalon Doctrine-Keeper to remove it.
This curse will cause some of what you type to have ranalon propaganda appended to the end of it, confusing communications.


Our signature Crystal Cut design presented in open box for lovely visual merchandising display and ready for point of sale.
Reclaim empty vessel for jewels, make up & florals.
With all x4 size variations to tell the "Oleria Emporium" story we find these Small Trinkets are a wonderful treat for those clients who adore our Larger pieces but can only need a small gift.


As I reflect back on my own journey learning about both English and Chinese in Singapore, the relative importance of these two languages actually reflect the rise of China against the backdrop of the only Superpower nation (United States) then after the collapse of the Soviet Union. In my younger days, the Chinese language is a language that I learn only because it was my "mother tongue". And I hardly used it outside the context of family and friendly banter with my Chinese friends. I realised that as China's economic clout increases, the importance of being able to communicate well in business Chinese has increased multifold. And while the miracle of technology have brought us tremendous progress in translation (such as Google Translate), I still need to be able to catch some of the nuances that only a human can currently catch that. The recent China-USA trade war reflects the threat that the Americans' perceive the Chinese to be. In the short term, both countries will be negatively affected but I believe in the mid to long term, these issues will turn in China's favour. I can only say that I wish I had been more diligent and master my Chinese language better when young! This therefore will be a special issue, where the main body of the newsletter is written in Mandarin by Joyce, with the English version below.
Throughout my life's journey, I have made mistakes that I wish I didn't. In the area of business and investing, there are lessons learnt earlier in my life that in retrospect could have been unnecessary. And this spans many areas, ranging from choosing the wrong companies to invest in, choosing and working with unsuitable team members, taking things or information at face value, and the list goes on. I wonder to myself if there is anything that I can do better to reduce, if not eliminate these sort of errors.
Eventually, I came to a phrase that will remind myself to (hopefully!) minimise such mistakes. That phrase is "Pay Attention". This short phrase may remind you of some teachers who, during your time, would always remind or even shout out to certain students in your class. Yet, as adults, I realise that many mistakes made were the result of not paying attention to certain details, or not focusing on the people in front of us or to the task at hand. In investing, as we run the financials through various quantitative tests, are we paying sufficient attention to not just make sure that the financials pass the benchmarks, but if they also make sense? When reviewing businesses/stocks, are we paying attention to the areas that matter instead of the areas that we prefer or like? From my observations, a person typically make mistakes in areas that he is unfamiliar or ignorant of. However, despite my constant reminders to myself, I would not say I'm totally attentive all the time. However, the phrase "pay attention" allows me to catch myself whenever I am not doing so.
During our investment team meetings, particularly in our discussions of individual companies, I would often seek to ask questions that support the team to determine if we have paid sufficient attention to the major areas. By having an aligned and capable team, with their respective strengths and weaknesses, enables us to pay attention to the different areas of a business and the stock. This allows questions and answers that may throw some doubts to the team's original thesis, and enable us as a team to cover more areas of a businesses that we would have otherwise miss as an individual.
In the end, what simply matters in investing is minimizing our losers and maximizing our winners. Paying attention to the relevant details in our investment process when assessing the various companies will support us in making sure that we can do so.
Ever since news about the US-China trade war broke out in March this year, the two major stock indexes in China have taken a tumble; the Shanghai stock index dropped 22%, Shenzhen stock index sank 31%, even the Hongkong index dropped 16%. The markets worldwide are in the red.
Readers of <<The Intelligent Investor>> would know that Benjamin Graham created the phrase "Mr. Market", which was probably the most brilliant metaphor ever created for explaining how stocks can become mis-priced. When he was asked why most investors failed , "The primary cause of failure is that they pay too much attention to what the stock market is doing currently." However, to be honest, how many people would be able to hold their nerves and ignore the movements Of the market? How many a time do you see the depiction of Wall Street having many traders jumping up and down the floor, spurred by the volatility of the stock market. Such scenes in movies are always exaggerated, but it depict perfectly the idea of the markets movements captivating people worldwide and influencing their emotions. With this knowledge, we can reflect if we are choosing to use Mr. Market to our advantage, or be led and influenced by him.
Emotions are often involved in any decisions we make, including investing. Although most of us are aware of this, we tend to ignore the fact that these emotions will affect our investment decisions unconsciously. We find that chances of investing well is closely related to In today's market conditions, where the market is in a state of emotional panic and there is deterioration of the macroeconomic factors, which may have led to the stock markets crashing, I find that there is is more interesting than analyzing the human psychology In when investing, and uncovering ways to help us avoid this psychological black hole.
In fact, the recent market crash has left me wondering if we could have executed our strategies better, had I had been immune to the market noises. For illustration purposes, I'll be diving into a few cases in point. Our fund is currently Monitoring a leading Chinese optical company, which positions itself in mid-to-high end product. It currently has a leading market share in handset lens, second only to the global No.1 supplier Taiwan's Largan Precision (TSEC:3008), and it Hold the No.1 global market share in both vehicle lens and handset cameras.
For the camera lens segment, the industry can be traced back to over a hundred years, and its technology has evolved many times: from the earliest film cameras to today's handset cameras. However, the industry has remained strong, and will do so in the Foreseeable future. For this segment, the company is able to count the current BIG FOUR brands in China (such as Huawei, Xiaomi, OPPO, and VIVO) as part of the company's main customers, and has recently gained Samsung as a customer for their Mobile phones in 2018.
For their Vehicle Lens segment, their customers including mainly the top-tiered brands such as Tesla, Mercedes-Benz, Volkswagen etc. We believe that the unique business specialisations of the company will help it strengthen its position in the industry, due to the close Co-operation needed between the lens and camera module.
The company has gained experience and the intangible know-how in optical design through manufacturing lenses since the traditional camera era, and are well positioned to capture sales in the upcoming trend of mobile camera technology of high-pixel, large-aperture and optical zoom design They are able to create synergies between the company's own lens and camera module businesses, further strengthening its position in the industry. Its Vehicle Lens sector also enjoys a certain entry barrier moat, due to its strict auditing conditions and long certification period in automobile industry .
The headline grouped Sunny Optical as part of Apple's group of concept stock, and together with the market downgrades of iPhone's shipment for the future, the Stock price reacted by falling. However, Sunny Optical does not provide products to Apple's mobile phones. Is this just market noise, or useful information that we can use? We must be able to discern the facts from speculation.
This news will no doubt affect Huawei, one of the main customers of Sunny. However, upon analyzing the market share of China's branded smartphones in the United States, each of them holds less than 2% of the top Six brands (see Table 1: Percentage of Chinese mobile phone market share in the US). Why worry about the sales of Chinese smartphones in the US? Is this just market noise, or useful information that we can use? Table 1 When it comes to investing, people seem to be Addicted to looking out for more information; as we are under the assumption that the more we know, the better we can make the correct judgement.
In the past, I had this bad habit: whenever the price of a stock fluctuates, I will constantly search for news that may shed some light on such movements. However, you will find that the majority of news available now are just market noises, But after constantly being fed these "noises", it is easy for people to forget the fundamentals and change their minds. When investing, mistakes can be made in an instant, or a moment; hence the saying: one moment in heaven How can we make sure that we are able to make sure that moment that we get will sure we land in paradise? Lao , one of the moments of the hell. Tzu once said: With more information, there's a higher chance one will get lost. Why? First of all, too much information will confuse you.
Secondly, news tend to be mixed with other people's opinions, affecting your judgement. The more information you receive, the harder it is to remain grounded, unsettling your state of mind. During his time, "investing" may not have existed, but yet I find the quote that he said extremely relatable to investing. To combat this, there is a ratio called the signal to noise ratio. Signal-to-noise ratio is a measure of how much useful information there is in a system, such as the Internet, as a proportion of the entire contents. With the popularity of information networks, the amount of information is in a state of blowout, and the information that is often useful in the stock market is covered by those noises, thus the ratio is very Low recently.
In such turbulent markets, we need to be able to clear our mind and find the true value of the investment along those noises. When investing, Less is more. For investors, the most important thing is to control their own behaviour and make rational investment The more information does not help us overcome our inner demons, we must build our own investment process and act on it to help us return to rational investment. For my conclusion, I have included key points from books of "Why smart people make big Money mistakes" and "The little book of behavioural investing" which I personally find very useful to guide us when investing, and can contribute to your investment process.
Only track the company's fundamentals, future developments, and industry-related content. Determine what kind of information is the useful information, and what is the noise. Taking the previous case as an example, please refer to Table 2 to focus on the factual state of the enterprise.
When the emotion comes, hold on first.
In the face of this stock market crash, it was a little unexpected, and the surprise led me to somewhat doubt my own judgment. As a member of the Hidden Champions Fund team, I am grateful for the trust and support of Clive, with help and insights from Zhipeng, Joshua and Jinliang, we are able to exchange our perspectives from different perspectives, with a focus on the facts, focusing on the process, to ensure the Fund is well protected. The road of investing is long and arduous, but together we will strive to uncover the best.
As time passes, with the benefit of hindsight, I would like to conclude by referring to Milan Kundera's quote and perhaps reflect: Have we crossed the chaotic rocks and obstacles of the market, and are we headed for the fertile shore that is value investing?


, choices the top collections having ideal image resolution exclusively for you all, and now this photographs is one of images series inside our greatest photos gallery about Bonfire Of the Vanities Summary. I really hope you'll like it.
put up by simply godong at 2018-09-19 18:05:14. To see all pictures in Bonfire Of the Vanities Summary pictures gallery please follow this kind of hyperlink.


text:
HomePosts tagged 'Fire Department'
Did You Know? More Fascinating Facts.
December 3, 2013 November 19, 2013 fasab Factoids, Unusual	Abraham Lincoln, achievement, adults, aerial combat, alarm system, alter-ego, American blues musicians, Bibles in hotels, bone, broken laser pointer, Charles Lindbergh, cigarette company, Clark Kent, Columbia, Columbia City, commercials, Daily Planet, devout Christian, Did You Know, Distinguished Flying Cross, education, educational, Entertainment, fabulous facts, fact, factoid, facts, Fascinating Facts, Fire Department, first American space station, first item sold on eBay, first recipient, Flintstones, Floyd Council, God, heroism, Honeywell International, hospitals, human body, hyoid bone, In God We Trust, information, Interesting Facts, Iron Mountain, kids, Larry, Larry Bird, leaves, lowest violent-crime rate in the US, Maine, military bases, Misc, Miscellaneous, money, Montana, nasa, neutered pets, neuticles, Pink Anderson, Pink Floyd, poinsettia, Presidency, prisons, Random, red petals, reporter for the Daily Star, sacrilege, Salmon Chase, Skylab, smoke detector, smoke or fire, sponsored, state of Minnesota, Stephen King, Superior Hotel, Superman, Syd Barrett, synthetic testicles, The Gideons, Theodore Roosevelt, transatlantic flight, Treasury Secretary, trivia, Twitter's bird logo, University of Minnesota, US currency, US homes, useful facts, Washington DC, Washington state, Winstons
Another 'Did You Know' day on the fasab blog.
More fascinating facts to ponder over.
The first item sold on eBay was a broken laser pointer.
A collector of broken laser pointers bought it for $14.83.
The first recipient of the Distinguished Flying Cross award
(for heroism or achievement in aerial combat)
was Charles Lindbergh.
He achieved this feat a year before his famous transatlantic flight.
The Gideons, who went on to place millions of Bibles
in hotels, prisons, hospitals and military bases,
first did so at the Superior Hotel in Iron Mountain, Montana, in 1908.
The poinsettia's red petals are actually leaves.
Superman's alter-ego, Clark Kent, originally worked
as a reporter for the Daily Star.
The Star changed its name to
the more familiar Daily Planet in 1940.
Washington State was supposed to be named "Columbia"
but the idea was scrapped because it was thought
it would be too easily confused with "Columbia City"
(today commonly referred to as Washington, D.C.).
Neuticles are synthetic testicles for neutered pets.
The tagline: "It's like nothing ever changed."
The Flintstones was sponsored by a cigarette company
during the show's first two seasons.
The show was intended for adults, not kids,
so few complained about the commercials that depicted
the stone-age characters puffing away on Winstons.
The hyoid bone is the only bone in the human body
not connected to another bone.
In 1973, NASA launched Skylab, the first American space station.
Three successive crews lived and worked there for more than 171 days.
Knowing a call to the fire department would accomplish precious
little from outer space, NASA and Honeywell International, Inc., developed
an alarm system that would alert the station's crew to smoke or fire.
The smoke detector used on the space station is the same kind
that is now found in 90 percent of U.S. homes.
Twitter's bird logo is named Larry,
for Larry Bird.
The University of Minnesota
is older than the state of Minnesota.
While Stephen King sets many of his stories in Maine,
the state actually has the lowest violent-crime rate in the U.S.
Printing the phrase "In God We Trust" on U.S. currency was a mandate
handed down by Abraham Lincoln's Treasury Secretary Salmon Chase.
During his presidency, Theodore Roosevelt attempted to remove the slogan
because he, as a devout Christian, felt that putting God on money was a sacrilege.
Syd Barrett got the name Pink Floyd from two American blues musicians,
Pink Anderson and Floyd Council.
As A Rule Of Thumb, Don't Pick Up Hitchhikers.
October 31, 2013 October 30, 2013 fasab comedy, Humour, Language, Puns	a cut, A-team, AA meeting, amusing, Anonymous, attire, bad jokes, beauty contest, boat, boos, burger king, car park, contract, conversation, cylindrical fasteners, driver, dropped out of school, drunken arguments, Fire Department, fruit and vegetable business, funny, girlfriend, Golly, Guns and Hoses, hacking group, heck, hitchhikers, Humor, humorous, Humour, hunch, internet, Japanese, job interview, joke, jokes, knives, ladder company, liquidation, lot, managing director, McDonald's, Miss Print, moat, models, motor boat, new job, news, newspaper pages, numbskull, off-piste, penpal, piggyback, play on words, police, posture, pun, pun day, puns, red blood cells, report to Reception, rival, riveting, rule of thumb, S and M club, Senseis, silly jokes, skiers, smoothies, stacking shelves, step down, stupid jokes, supermarket, vein, word play, word plays
But as a rule of thumb I like puns.
Hope you do too.
Here are some more.
My Japanese penpal dropped out of school recently.
He's taken leave of his Senseis.
I've got a new job stacking shelves at a supermarket for big, tall men.
It keeps me on my toes.
I was chatting to someone about cylindrical fasteners earlier,
it was a riveting conversation.
Skiers don't have drunken arguments,
they just storm off-piste.
I used to be the managing director of the world's largest ladder company.
Until I was asked to step down.
A friend asked if I wanted to buy his motor boat.
I jumped at the chance and bought both.
I can keep the boat on the moat.
My friend sells knives for a living and he said if I posted
this on the internet he'd give me a cut.
What numbskull called it the Police / Fire Department Headquarters
and not Guns and Hoses?
I went for a job interview with the hacking group Anonymous.
Introduced myself…
And that was the end of the interview
Just read in the news, that there's going to be a beauty contest
where all the models are dressed up in newspaper pages.
It must be a Miss Print.
The A- eam.
Hey, missed a T.
I went through a lot to be with my girlfriend.
She was standing at the other end of the car park.
I wish I'd never joined the S and M club.
They tied me into a long term contract.
A driver waved at me to stop my car and asked if I could change attire.
Why would someone assume that I would keep spare clothes with me!
Heck is where people go to
who don't believe in Golly.
Something tells me my posture might not be so great,
I just have a hunch.
Two red blood cells met and fell in love.
But alas, it was in vein.
My fruit and vegetable business has gone into liquidation.
Now we sell smoothies.
Man, you get a load of boos when
you turn up to an AA meeting pissed.
I turned up to a McDonald's job interview
riding piggyback on a Burger King employee.
"Could I just ask what the hell you're doing?"
the receptionist asked curtly.
"Well," I explained patiently, "the woman on the phone told me
I should report to Reception on a rival"

redpajama_set_name: RedPajamaCommonCrawl


text:
El periosti (peri = al voltant, i osti = os) és una membrana de teixit connectiu molt vascularitzada, fibrosa i resistent, que cobreix l'os per la seva superfície externa, excepte en llocs d'inserció de lligaments, tendons, i superfícies articulars (la superfície externa de l'os a nivell de les articulacions està coberta per cartílag hialí, anomenat cartílag articular).

El periosti posseeix terminacions nervioses nociceptives, que el fan molt sensible a la manipulació. Mitjançant la irrigació sanguínia proveeix a l'os els nutrients que necessita. Es troba unit a l'os per fortes fibres de col·lagen anomenades fibres de Sharpey, que s'estenen a les lameles circumferencials externes i intersticials.

El periosti està format per una capa externa fibrosa i una capa interna de recanvi. La capa fibrosa conté fibroblasts, mentre que la capa de recanvi conté cèl·lules progenitores que es transformen en osteoblasts, que són responsables de l'augment del gruix de l'os. Després d'una fractura òssia les cèl·lules progenitores es transformen en osteoblasts i condroblasts, els quals són essencials en el procés de curació.

Histologia

redpajama_set_name: RedPajamaWikipedia


The new Metric Hoopster Retaining Rings offer an innovative way to retain mechanical components when space is a problem. The Hoopster's minimal radial projection and shallow groove depth allow it to fit where regular stamped rings and retaining rings cannot. The Hoopster's low profile, precision circularity and small radial size allow it to be an unobtrusive component in an assembly. Hoopster Retaining Rings are suitable for light to heavy loads and are ideal for thin-wall tubes.
Cover Image: Is GM's Volt Squad a glimpse of future law enforcement?
Building an N-gauge (1:160) model train system involves working with very small units. The 1930s-inspired BR 70 locomotive from Fleischmann is only about 58 mm long when measured buffer to buffer. As on large locomotives, traction (and on the model, power transmission) between the wheel and the track is a crucial factor. To give the unit appropriately scaled big-train power with low vibration and noise, the folks at Fleischmann turned to customized DC motors from the FAULHABER Group.
Stephane Cros, an experienced kite surfer, took a fearless approach to learning 3D computer-aided design and prototyping for the development of his CAMRIG universal camera-mount product. Luckily, he had a little plastics design help along the way.
A Pennsylvania company called Ecospan says it's breaking new ground when it comes to delivering sustainable solutions to the plastics we use every day.
Scientists at the University of Glasgow in Scotland have developed a practical solution to the increasing problem of space debris: a lightweight, foldable aerobrake that can be deployed to help decommission a small satellite at the end of its lifecycle.
Redfish Instruments' iDVM is the world's first Apple-enabled multimeter that wirelessly connects to an iPhone, iPad, or iPod Touch, allowing users to easily acquire, visualize, and share electrical measurements. Available from Saelig, this unique voltmeter measures voltage, current, and resistance, and is an ideal solution for making isolated measurements at up to 30 m. Users can acquire data, save it, email it, post it to a Web server, or display it for further visualization. Using the iOS integrated speech function, the iDVM can even "speak" the measurement. Uses rechargeable batteries. The iDVM app, with its familiar appearance of a standard digital voltmeter, can be downloaded free from the Apple App Store.
Mark-10 introduces their Series 2 digital force gauges, designed for basic tension and compression force testing in quality control, manufacturing, and R&D areas in virtually every industry. A range of capacities from 2 lb to 100 lb (10 N to 500 N) is available to address numerous applications. Accuracy is better than +/-0.5 percent of full scale, and overload protection is provided to 150 percent of capacity. The force gauges feature a sampling rate of 500 Hz, large, backlit graphic display, and simple, intuitive menu structure for quick access to features and configurable parameters. Series 2 is powered by a 9-V battery and may also be used with an optional AC adapter.
A new comprehensive product bulletin available free from PennEngineering profiles the complete line of microPEM fasteners ideally suited for attachment applications in compact electronic assemblies. These extremely small fasteners can serve as practical, cost-effective, and permanently secure solutions enabling quicker assembly of devices ranging from hand-held consumer electronics -- including tablets, phones, and laptops -- to medical equipment, among others.
The HD Series servo system solution from Servotronix Motion Control features a high-performance digital servo drive (CDHD) with a high-precision AC servo motor (MTHD). The combined servo drive and motor are optimized for best performance, offering advanced functionality, high power density, and seamless commissioning in a cost-effective package. HD Series incorporates a new current-loop design that achieves an industry-leading frequency response up to 3 kHz. An active non-linear Anti-Vibration algorithm eliminates vibration in highly flexible resonant systems.
Automakers General Motors, Volkswagen, and BMW are developing thermoelectric generators that recover waste heat from commercial car and SUV combustion engines and reuse it as electricity. Now the U.S. military wants in on the technology, too.
When the U.S. Navy's USS Makin Island leaves base, it does not steam across the ocean. It motors.
With satellites playing increasingly important roles in everyday life, NASA is developing the technology to build Earth-orbiting, roving "service stations" capable of extending the life of these spacecraft.
For those dreaming of what it actually feels like to be a jet pilot or Indy race car driver, look no further than Force-Dynamics' Motion Simulator Systems (MSS). The experience is so realistic that you can actually feel the G-forces against your body during acceleration and bounce to every nook and bump on the road. The Galil DMC-2133 3-axis Ethernet motion controller is used in Force Dynamics' 301 3-axis platform, which provides +/- 30 degrees of roll, pitch, and heave motion. The DMC-2143 4-axis controller is used in the 401CR 4-axis model, which adds 360 degrees of unlimited yaw motion and a whole lot more fun.


iMacsoft iPad to Mac Transfer, the excellent iPad to Mac transfer, is specially designed for Mac users to fast transfer, rip, copy and manage your music, video, photo, ePub, pdf, audiobook, podcast and TV Show files from iPad to Mac, iPad to iTunes.... 3/09/2016 · I have the latest version (7.9.318138) of Evernote installed on my new iPad Pro (128Gb, WiFi). On notes (old or new) which have a .pdf file attached, when I tap the "Tap to Download" area, it does not load the document, it just enters the note as if editing.
View and Download Apple IPad user manual online. For iOS 8.1 Software. IPad Tablet pdf manual download.
Download The Hunger Games Trilogy PDF eBook 1-3 by Suzanne Collins torrent or any other torrent from the Other E-books. Direct download via magnet link.
Mockingjay pdf mobile9 - pdf download Posts To Page.In Catching Fire, you open the download lite app search for The Hunger Games PDF. mockingjay pdf mobile9 Mockingjay pdf sandra ignacio - pdf sandra ignacio Mockingjay pdf sandra ignacio the constables of San Ignacio could find no trace.


text:
package org.dcm4chex.archive.dcm.storescp;

import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.rmi.RemoteException;
import java.security.DigestInputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.ejb.ObjectNotFoundException;
import javax.management.ObjectName;
import javax.security.auth.Subject;

import org.dcm4che.data.Command;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmDecodeParam;
import org.dcm4che.data.DcmElement;
import org.dcm4che.data.DcmEncodeParam;
import org.dcm4che.data.DcmObjectFactory;
import org.dcm4che.data.DcmParser;
import org.dcm4che.data.DcmParserFactory;
import org.dcm4che.data.PersonName;
import org.dcm4che.dict.Status;
import org.dcm4che.dict.Tags;
import org.dcm4che.dict.UIDs;
import org.dcm4che.dict.VRs;
import org.dcm4che.net.AAssociateAC;
import org.dcm4che.net.AAssociateRQ;
import org.dcm4che.net.ActiveAssociation;
import org.dcm4che.net.Association;
import org.dcm4che.net.AssociationListener;
import org.dcm4che.net.DcmServiceBase;
import org.dcm4che.net.DcmServiceException;
import org.dcm4che.net.Dimse;
import org.dcm4che.net.PDU;
import org.dcm4che.util.BufferedOutputStream;
import org.dcm4che2.audit.message.AuditMessage;
import org.dcm4che2.audit.message.ParticipantObject;
import org.dcm4che2.audit.message.PatientRecordMessage;
import org.dcm4cheri.util.StringUtils;
import org.dcm4chex.archive.codec.CompressCmd;
import org.dcm4chex.archive.common.Availability;
import org.dcm4chex.archive.common.PrivateTags;
import org.dcm4chex.archive.common.SeriesStored;
import org.dcm4chex.archive.config.CompressionRules;
import org.dcm4chex.archive.ejb.conf.AttributeFilter;
import org.dcm4chex.archive.ejb.interfaces.FileDTO;
import org.dcm4chex.archive.ejb.interfaces.FileSystemDTO;
import org.dcm4chex.archive.ejb.interfaces.FileSystemMgt2;
import org.dcm4chex.archive.ejb.interfaces.FileSystemMgt2Home;
import org.dcm4chex.archive.ejb.interfaces.MPPSManager;
import org.dcm4chex.archive.ejb.interfaces.MPPSManagerHome;
import org.dcm4chex.archive.ejb.interfaces.Storage;
import org.dcm4chex.archive.ejb.interfaces.StorageHome;
import org.dcm4chex.archive.ejb.interfaces.StudyPermissionDTO;
import org.dcm4chex.archive.ejb.jdbc.QueryFilesCmd;
import org.dcm4chex.archive.exceptions.NonUniquePatientIDException;
import org.dcm4chex.archive.mbean.HttpUserInfo;
import org.dcm4chex.archive.perf.PerfCounterEnum;
import org.dcm4chex.archive.perf.PerfMonDelegate;
import org.dcm4chex.archive.perf.PerfPropertyEnum;
import org.dcm4chex.archive.util.EJBHomeFactory;
import org.dcm4chex.archive.util.FileUtils;
import org.dcm4chex.archive.util.HomeFactoryException;
import org.jboss.logging.Logger;

/**
 * @author Gunter.Zeilinger@tiani.com
 * @version $Revision: 18246 $
 * @since 03.08.2003
 */
public class StoreScp extends DcmServiceBase implements AssociationListener {

    private static final String ALL = "ALL";

    private static final int MISSING_USER_ID_ERR_STATUS = 0xCE10;

    private static final int NO_APPEND_PERMISSION_ERR_STATUS = 0xCE24;

    private static final String MISSING_USER_ID_ERR_MSG = "Missing user identification for appending existing Study";

    private static final String NO_APPEND_PERMISSION_ERR_MSG = "No permission to append existing Study";

    private static final String STORE_XSL = "cstorerq.xsl";

    private static final String STORE_XML = "-cstorerq.xml";

    private static final String MWL2STORE_XSL = "mwl-cfindrsp2cstorerq.xsl";

    private static final String STORE2MWL_XSL = "cstorerq2mwl-cfindrq.xsl";

    private static final String RECEIVE_BUFFER = "RECEIVE_BUFFER";

    private static final String SERIES_STORED = "SERIES_STORED";

//    private static final String SOP_IUIDS = "SOP_IUIDS";

    protected final StoreScpService service;

    private final Logger log;

    private boolean studyDateInFilePath = false;

    private boolean sourceAETInFilePath = false;

    private boolean yearInFilePath = true;

    private boolean monthInFilePath = true;

    private boolean dayInFilePath = true;

    private boolean hourInFilePath = false;

    private boolean acceptMissingPatientID = true;

    private boolean acceptMissingPatientName = true;

    private boolean serializeDBUpdate = false;

    private int updateDatabaseMaxRetries = 2;

    private int maxCountUpdateDatabaseRetries = 0;

    private boolean storeDuplicateIfDiffMD5 = true;

    private boolean storeDuplicateIfDiffHost = true;

    private long updateDatabaseRetryInterval = 0L;

    private CompressionRules compressionRules = new CompressionRules("");

    private String[] coerceWarnCallingAETs = {};

    private String[] acceptMismatchIUIDCallingAETs = {};

    private String[] onlyWellKnownInstancesCallingAETs = {};

    private boolean checkIncorrectWorklistEntry = true;

    private String[] referencedDirectoryPath;

    private String[] referencedDirectoryURI;

    private String refFileSystemGroupID;

    private boolean readReferencedFile = true;

    private boolean md5sumReferencedFile = true;

    private boolean coerceBeforeWrite = false;

    protected PerfMonDelegate perfMon;

    private volatile Executor syncFileExecutor;

    public StoreScp(StoreScpService service) {
        this.service = service;
        this.log = service.getLog();
        perfMon = new PerfMonDelegate(this.service);
    }

    public final ObjectName getPerfMonServiceName() {
        return perfMon.getPerfMonServiceName();
    }

    public final void setPerfMonServiceName(ObjectName perfMonServiceName) {
        perfMon.setPerfMonServiceName(perfMonServiceName);
    }

    public final boolean isAcceptMissingPatientID() {
        return acceptMissingPatientID;
    }

    public final void setAcceptMissingPatientID(boolean accept) {
        this.acceptMissingPatientID = accept;
    }

    public final boolean isAcceptMissingPatientName() {
        return acceptMissingPatientName;
    }

    public final void setAcceptMissingPatientName(boolean accept) {
        this.acceptMissingPatientName = accept;
    }

    public final boolean isSerializeDBUpdate() {
        return serializeDBUpdate;
    }

    public final void setSerializeDBUpdate(boolean serialize) {
        this.serializeDBUpdate = serialize;
    }

    public final String getCoerceWarnCallingAETs() {
        return StringUtils.toString(coerceWarnCallingAETs, '\\');
    }

    public final void setCoerceWarnCallingAETs(String aets) {
        coerceWarnCallingAETs = StringUtils.split(aets, '\\');
    }

    public final String getAcceptMismatchIUIDCallingAETs() {
        return StringUtils.toString(acceptMismatchIUIDCallingAETs, '\\');
    }

    public final void setAcceptMismatchIUIDCallingAETs(String aets) {
        acceptMismatchIUIDCallingAETs = StringUtils.split(aets, '\\');
    }

    public final String getOnlyWellKnownInstancesCallingAETs() {
        return StringUtils.toString(onlyWellKnownInstancesCallingAETs, '\\');
    }

    public final void setOnlyWellKnownInstancesCallingAETs(String aets) {
        onlyWellKnownInstancesCallingAETs = StringUtils.split(aets, '\\');
    }

    public final boolean isStudyDateInFilePath() {
        return studyDateInFilePath;
    }

    public final void setStudyDateInFilePath(boolean studyDateInFilePath) {
        this.studyDateInFilePath = studyDateInFilePath;
    }

    public final boolean isSourceAETInFilePath() {
        return sourceAETInFilePath;
    }

    public final void setSourceAETInFilePath(boolean sourceAETInFilePath) {
        this.sourceAETInFilePath = sourceAETInFilePath;
    }

    public final boolean isYearInFilePath() {
        return yearInFilePath;
    }

    public final void setYearInFilePath(boolean yearInFilePath) {
        this.yearInFilePath = yearInFilePath;
    }

    public final boolean isMonthInFilePath() {
        return monthInFilePath;
    }

    public final void setMonthInFilePath(boolean monthInFilePath) {
        this.monthInFilePath = monthInFilePath;
    }

    public final boolean isDayInFilePath() {
        return dayInFilePath;
    }

    public final void setDayInFilePath(boolean dayInFilePath) {
        this.dayInFilePath = dayInFilePath;
    }

    public final boolean isHourInFilePath() {
        return hourInFilePath;
    }

    public final void setHourInFilePath(boolean hourInFilePath) {
        this.hourInFilePath = hourInFilePath;
    }

    public final String getReferencedDirectoryPath() {
        if (referencedDirectoryPath == null)
            return ALL;
        StringBuffer sb = new StringBuffer();
        String nl = System.getProperty("line.separator", "\n");
        for ( String s : referencedDirectoryPath) {
            sb.append(s).append(nl);
        }
        return sb.toString();
    }

    public final void setReferencedDirectoryPath(String pathOrURI) {
        if ( ALL.equals(pathOrURI.trim())) {
            referencedDirectoryURI = null;
            referencedDirectoryPath = null;
        } else  {
            StringTokenizer st = new StringTokenizer(pathOrURI, " \t\r\n;");
            int len = st.countTokens();
            referencedDirectoryURI = new String[len];
            referencedDirectoryPath = new String[len];
            String trimmed;
            for ( int i = 0 ; st.hasMoreElements() ; i++ ) {
                trimmed = st.nextToken().trim();
                referencedDirectoryURI[i] = isURI(trimmed) ? (trimmed + '/') :
                    FileUtils.toFile(trimmed).toURI().toString();
                referencedDirectoryPath[i] = trimmed;
            }
        }
    }

    public void setReferencedFileSystemGroupID(String groupID) {
        this.refFileSystemGroupID = groupID;
    }

    public String getReferencedFileSystemGroupID() {
        return refFileSystemGroupID;
    }

    private static boolean isURI(String pathOrURI) {
        return pathOrURI.indexOf(':') > 1 ;
    }

    public final boolean isMd5sumReferencedFile() {
        return md5sumReferencedFile;
    }

    public final void setMd5sumReferencedFile(boolean md5ReferencedFile) {
        this.md5sumReferencedFile = md5ReferencedFile;
    }

    public final boolean isCoerceBeforeWrite() {
        return this.coerceBeforeWrite;
    }

    public final void setCoerceBeforeWrite(boolean coerceBeforeWrite) {
        this.coerceBeforeWrite = coerceBeforeWrite;
    }

    public final boolean isReadReferencedFile() {
        return readReferencedFile;
    }

    public final void setReadReferencedFile(boolean readReferencedFile) {
        this.readReferencedFile = readReferencedFile;
    }

    public final boolean isStoreDuplicateIfDiffHost() {
        return storeDuplicateIfDiffHost;
    }

    public final void setStoreDuplicateIfDiffHost(boolean storeDuplicate) {
        this.storeDuplicateIfDiffHost = storeDuplicate;
    }

    public final boolean isStoreDuplicateIfDiffMD5() {
        return storeDuplicateIfDiffMD5;
    }

    public final void setStoreDuplicateIfDiffMD5(boolean storeDuplicate) {
        this.storeDuplicateIfDiffMD5 = storeDuplicate;
    }

    public final CompressionRules getCompressionRules() {
        return compressionRules;
    }

    public final void setCompressionRules(CompressionRules compressionRules) {
        this.compressionRules = compressionRules;
    }

    public final int getUpdateDatabaseMaxRetries() {
        return updateDatabaseMaxRetries;
    }

    public final void setUpdateDatabaseMaxRetries(int updateDatabaseMaxRetries) {
        this.updateDatabaseMaxRetries = updateDatabaseMaxRetries;
    }

    public final int getMaxCountUpdateDatabaseRetries() {
        return maxCountUpdateDatabaseRetries;
    }

    public final void setMaxCountUpdateDatabaseRetries(int count) {
        this.maxCountUpdateDatabaseRetries = count;
    }

    public final long getUpdateDatabaseRetryInterval() {
        return updateDatabaseRetryInterval;
    }

    public final void setUpdateDatabaseRetryInterval(long interval) {
        this.updateDatabaseRetryInterval = interval;
    }

    /**
     * @return Returns the checkIncorrectWorklistEntry.
     */
    public boolean isCheckIncorrectWorklistEntry() {
        return checkIncorrectWorklistEntry;
    }

    /**
     * @param checkIncorrectWorklistEntry
     *                The checkIncorrectWorklistEntry to set.
     */
    public void setCheckIncorrectWorklistEntry(
            boolean checkIncorrectWorklistEntry) {
        this.checkIncorrectWorklistEntry = checkIncorrectWorklistEntry;
    }

    protected void doCStore(ActiveAssociation activeAssoc, Dimse rq,
            Command rspCmd) throws IOException, DcmServiceException {
        InputStream in = rq.getDataAsStream();
        perfMon.start(activeAssoc, rq, PerfCounterEnum.C_STORE_SCP_OBJ_IN);
        perfMon.setProperty(activeAssoc, rq, PerfPropertyEnum.REQ_DIMSE, rq);

        DcmDecodeParam decParam = DcmDecodeParam.valueOf(rq
                .getTransferSyntaxUID());
        Dataset ds = objFact.newDataset();
        DcmParser parser = DcmParserFactory.getInstance().newDcmParser(in);
        parser.setMaxValueLength(service.getMaxValueLength());
        parser.setDcmHandler(ds.getDcmHandler());
        parser.parseDataset(decParam, Tags.PixelData);
        if (!parser.hasSeenEOF() && parser.getReadTag() != Tags.PixelData) {
            parser.unreadHeader();
            parser.parseDataset(decParam, -1);
        }
        doActualCStore(activeAssoc, rq, rspCmd, ds, parser);

        perfMon.stop(activeAssoc, rq, PerfCounterEnum.C_STORE_SCP_OBJ_IN);
    }

    /**
     * Actual CStore request handling. Allows for subclasses to do some
     * preliminary work with the rq Dataset before reading and handling the
     * pixel data.
     *
     * This method expects that the Dataset has already been parsed from the
     * Dimse InputStream, and the DcmParser is initialized already with the
     * Dataset.
     *
     * @param activeAssoc
     *                The ActiveAssociation
     * @param rq
     *                The Dimse request
     * @param rspCmd
     *                The response Command
     * @param ds
     *                The parsed Dataset from the Dimse rq
     * @param parser
     *                The DcmParser initialized with the InputStream from the
     */
    protected void doActualCStore(ActiveAssociation activeAssoc, Dimse rq,
            Command rspCmd, Dataset ds, DcmParser parser) throws IOException,
            DcmServiceException {
        File file = null;
        boolean dcm4cheeURIReferenced = rq.getTransferSyntaxUID().equals(
                UIDs.Dcm4cheURIReferenced);
        try {
            Command rqCmd = rq.getCommand();
            Association assoc = activeAssoc.getAssociation();
            String callingAET = assoc.getCallingAET();
            String originalCallingAET = service.getOriginalCallingAET(ds, callingAET);
            String calledAET = assoc.getCalledAET();
            String iuid = checkSOPInstanceUID(rqCmd, ds, originalCallingAET);
            checkAppendPermission(assoc, ds);
            if (!checkOnlyWellKnownInstances(assoc, iuid, originalCallingAET)) {
                log.info("StoreSCP only accepts well known instances from AE "+ originalCallingAET+
                        " ! Ignored Instance:"+iuid);
                return;
            }
            List duplicates = new QueryFilesCmd(iuid).getFileDTOs();
            if (!(duplicates.isEmpty() || storeDuplicateIfDiffMD5 || storeDuplicateIfDiffHost
                    && !containsLocal(duplicates))) {
                log.info("Received Instance[uid=" + iuid
                        + "] already exists - ignored");
                return;
            }

            service.preProcess(ds);

            if (log.isDebugEnabled()) {
                log.debug("Dataset:\n");
                log.debug(ds);
            }

            // Set original dataset
            perfMon.setProperty(activeAssoc, rq, PerfPropertyEnum.REQ_DATASET,
                    ds);

            service.logDIMSE(assoc, STORE_XML, ds);
            if (isCheckIncorrectWorklistEntry()
                    && checkIncorrectWorklistEntry(ds)) {
                log
                        .info("Received Instance[uid="
                                + iuid
                                + "] ignored! Reason: Incorrect Worklist entry selected!");
                return;
            }
            String retrieveAET;
            String availability;
            FileSystemDTO fsDTO = null;
            String filePath = null;
            byte[] md5sum = null;
            Dataset coerced = service.getCoercionAttributesFor(callingAET,
                    STORE_XSL, ds, assoc);
            if ( coerceBeforeWrite ) {
                ds.setPrivateCreatorID(PrivateTags.CreatorID);
                ds.putAE(PrivateTags.CallingAET, originalCallingAET);
                ds.putAE(PrivateTags.CalledAET, calledAET);
                ds.setPrivateCreatorID(null);
                if (coerced != null) {
                    service.coerceAttributes(ds, coerced);
                }
                service.postCoercionProcessing(ds);
            }
            if (dcm4cheeURIReferenced) {
                String uri = ds.getString(Tags.RetrieveURI);
                if (uri == null) {
                    retrieveAET = ds.getString(Tags.RetrieveAET);
                    availability = ds.getString(Tags.InstanceAvailability);
                    if (retrieveAET == null || availability == null ) {
                        throw new DcmServiceException(
                                Status.DataSetDoesNotMatchSOPClassError,
                                "Missing (0040,E010) Retrieve URI - required for Dcm4che Retrieve URI Transfer Syntax");
                    }
                } else {
                    String[] selected = selectReferencedDirectoryURI(uri);
                    if (selected == null) {
                        throw new DcmServiceException(
                                Status.DataSetDoesNotMatchSOPClassError,
                                "(0040,E010) Retrieve URI: " + uri
                                + " does not match with configured Referenced Directory Path: "
                                + getReferencedDirectoryPath());
                    }
                    filePath = uri.substring(selected[1].length());
                    if (uri.startsWith("file:/")) {
                        file = new File(new URI(uri));
                        if (!file.isFile()) {
                            throw new DcmServiceException(Status.ProcessingFailure,
                                    "File referenced by (0040,E010) Retrieve URI: "
                                            + uri + " not found!");
                        }
                    }
                    fsDTO = getFileSystemMgt().getFileSystemOfGroup(
                            refFileSystemGroupID, selected[0].startsWith("file:") ?
                                    new URI(selected[0]).getPath() : selected[0]);
                    retrieveAET = fsDTO.getRetrieveAET();
                    availability = Availability.toString(fsDTO.getAvailability());
                    if (file != null && readReferencedFile) {
                        log.info("M-READ " + file);
                        Dataset fileDS = objFact.newDataset();
                        FileInputStream fis = new FileInputStream(file);
                        try {
                            if (md5sumReferencedFile) {
                                MessageDigest digest = MessageDigest
                                        .getInstance("MD5");
                                DigestInputStream dis = new DigestInputStream(fis,
                                        digest);
                                BufferedInputStream bis = new BufferedInputStream(
                                        dis);
                                fileDS.readFile(bis, null, Tags.PixelData);
                                byte[] buf = getByteBuffer(assoc);
                                while (bis.read(buf) != -1)
                                    ;
                                md5sum = digest.digest();
                            } else {
                                BufferedInputStream bis = new BufferedInputStream(
                                        fis);
                                fileDS.readFile(bis, null, Tags.PixelData);
                            }
                        } finally {
                            fis.close();
                        }
                        fileDS.putAll(ds, Dataset.REPLACE_ITEMS);
                        ds = fileDS;
                    } else {
                        ds.setPrivateCreatorID(PrivateTags.CreatorID);
                        String tsuid = ds.getString(
                                PrivateTags.Dcm4cheURIReferencedTransferSyntaxUID,
                                UIDs.ImplicitVRLittleEndian);
                        ds.setPrivateCreatorID(null);
                        ds.setFileMetaInfo(objFact.newFileMetaInfo(rqCmd
                                .getAffectedSOPClassUID(), rqCmd
                                .getAffectedSOPInstanceUID(), tsuid));
                    }
                }
            } else {
                String fsgrpid = service.selectFileSystemGroup(originalCallingAET, ds);
                fsDTO = service.selectStorageFileSystem(fsgrpid);
                retrieveAET = fsDTO.getRetrieveAET();
                availability = Availability.toString(fsDTO.getAvailability());
                File baseDir = FileUtils.toFile(fsDTO.getDirectoryPath());
                file = makeFile(baseDir, ds, originalCallingAET);
                filePath = file.getPath().substring(
                        baseDir.getPath().length() + 1).replace(
                        File.separatorChar, '/');
                CompressCmd compressCmd = null;
                if (parser.getReadTag() == Tags.PixelData
                        && parser.getReadLength() != -1) {
                    compressCmd = compressionRules.getCompressFor(assoc, ds);
                    if (compressCmd != null)
                        compressCmd.coerceDataset(ds);
                }
                ds.setFileMetaInfo(objFact.newFileMetaInfo(ds,
                        compressCmd != null
                            ? compressCmd.getTransferSyntaxUID()
                            : rq.getTransferSyntaxUID()));

                perfMon.start(activeAssoc, rq,
                        PerfCounterEnum.C_STORE_SCP_OBJ_STORE);
                perfMon.setProperty(activeAssoc, rq,
                        PerfPropertyEnum.DICOM_FILE, file);
                md5sum = storeToFile(parser, ds, file, compressCmd, getByteBuffer(assoc));

                String creatorId = ds.getPrivateCreatorID();
                ds.setPrivateCreatorID(PrivateTags.CreatorID);
                boolean containsPostPixeldata = ds.contains(PrivateTags.InstanceContainsPostPixelData);
                ds.setPrivateCreatorID(creatorId);

                if (containsPostPixeldata) {
                	log.info("Instance[uid=" + iuid
                			+ "] has post pixel data. Rewriting file to include indicator flag");

                	FileInputStream fis = new FileInputStream(file);
                	BufferedInputStream bis = new BufferedInputStream(fis);
                	Dataset fileDs = objFact.newDataset();

                	DcmParser fileParser = DcmParserFactory.getInstance().newDcmParser(bis);
                	fileParser.setMaxValueLength(service.getMaxValueLength());
                	fileParser.setDcmHandler(fileDs.getDcmHandler());
                	fileParser.parseDcmFile(null, -1);
                	putPrivatePostPixelIndicator(fileDs);

                	File postPixelDataFile = makeFile(baseDir, fileDs, originalCallingAET);
                	md5sum = storeToFile(fileParser, fileDs, postPixelDataFile, compressCmd, getByteBuffer(assoc));

                	bis.close();
                	deleteFailedStorage(file);
                	file = postPixelDataFile;
                	filePath = file.getPath().substring(
                			baseDir.getPath().length() + 1).replace(
                					File.separatorChar, '/');
                }

                perfMon.stop(activeAssoc, rq,
                        PerfCounterEnum.C_STORE_SCP_OBJ_STORE);
            }
            if (md5sum != null && ignoreDuplicate(duplicates, md5sum)) {
                log.info("Received Instance[uid=" + iuid
                        + "] already exists - ignored");
                if (!dcm4cheeURIReferenced) {
                    deleteFailedStorage(file);
                }
                return;
            }
            ds.putAE(Tags.RetrieveAET, retrieveAET);
            if ( ! coerceBeforeWrite ) {
                ds.setPrivateCreatorID(PrivateTags.CreatorID);
                ds.putAE(PrivateTags.CallingAET, originalCallingAET);
                ds.putAE(PrivateTags.CalledAET, calledAET);
                ds.setPrivateCreatorID(null);
                if (coerced != null) {
                    service.coerceAttributes(ds, coerced);
                }
                service.postCoercionProcessing(ds);
            }
            checkPatientIdAndName(ds, originalCallingAET);
            Storage store = getStorage(assoc);
            String seriuid = ds.getString(Tags.SeriesInstanceUID);

            SeriesStored seriesStored = this.getSeriesStored(assoc, seriuid);
            this.notifyOnSeriesStored(seriesStored, assoc, store, seriuid);

            boolean newSeries = seriesStored == null;
            boolean newStudy = false;
            if (newSeries) {
                Dataset mwlFilter = service.getCoercionAttributesFor(callingAET,
                        STORE2MWL_XSL, ds, assoc);
                if (mwlFilter != null) {
                    coerced = merge(coerced, mergeMatchingMWLItem(assoc, ds,
                            seriuid, mwlFilter));
                }
                if (!originalCallingAET.equals(calledAET)) {
                    service.ignorePatientIDForUnscheduled(ds,
                            Tags.RequestAttributesSeq, originalCallingAET);
                    service.supplementInstitutionalData(ds, originalCallingAET);
                    service.generatePatientID(ds, ds, calledAET);
                }
                newStudy = !store.studyExists(ds.getString(Tags.StudyInstanceUID));
            }
            perfMon.start(activeAssoc, rq,
                    PerfCounterEnum.C_STORE_SCP_OBJ_REGISTER_DB);
            long fileLength = file != null ? file.length() : 0L;
            long fspk = fsDTO != null ? fsDTO.getPk() : -1L;
            Dataset coercedElements;
            try {
                coercedElements = updateDB(store, ds, fspk, filePath,
                        fileLength, md5sum, md5sum, newSeries);
            } catch (NonUniquePatientIDException e) {
                service.coercePatientID(ds);
                coerced.putLO(Tags.PatientID, ds.getString(Tags.PatientID));
                coerced.putLO(Tags.IssuerOfPatientID,
                        ds.getString(Tags.IssuerOfPatientID));
                coercedElements = updateDB(store, ds, fspk, filePath,
                        fileLength, md5sum, md5sum, newSeries);
            }

		    	seriesStored = setSeriesStored(ds, assoc, callingAET, fsDTO,
					seriesStored, newSeries, seriuid);
            if(newSeries && newStudy) {
                   service.sendNewStudyNotification(ds);
            }
            appendInstanceToSeriesStored(seriesStored, ds, retrieveAET, availability);
            coerced = merge(coerced, coercedElements);
            logCoercion(ds, coerced);
            ds.putAll(coercedElements, Dataset.MERGE_ITEMS);

            perfMon.setProperty(activeAssoc, rq, PerfPropertyEnum.REQ_DATASET,
                    ds);
            perfMon.stop(activeAssoc, rq,
                    PerfCounterEnum.C_STORE_SCP_OBJ_REGISTER_DB);
            if (coerced.isEmpty()
                    || !contains(coerceWarnCallingAETs, callingAET)) {
                rspCmd.putUS(Tags.Status, Status.Success);
            } else {
                int[] coercedTags = new int[coerced.size()];
                Iterator it = coerced.iterator();
                for (int i = 0; i < coercedTags.length; i++) {
                    coercedTags[i] = ((DcmElement) it.next()).tag();
                }
                rspCmd.putAT(Tags.OffendingElement, coercedTags);
                rspCmd.putUS(Tags.Status, Status.CoercionOfDataElements);
            }
            service.postProcess(ds);
        } catch (DcmServiceException e) {
            log.warn(e.getMessage(), e);
            if (!dcm4cheeURIReferenced) {
                deleteFailedStorage(file);
            }
            throw e;
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            if (!dcm4cheeURIReferenced) {
                deleteFailedStorage(file);
            }
            throw new DcmServiceException(Status.ProcessingFailure, e);
        }
    }

    private void logCoercion(Dataset ds, Dataset coerced) {
    	if ( coerced.size() > 0 ) {
    		StringBuilder sb = new StringBuilder();
    		for ( Iterator<DcmElement> i = coerced.iterator(); i.hasNext(); ) {
    			DcmElement coercedElement = i.next();
    			DcmElement originalElement = ds.get(coercedElement.tag());
    			if ( originalElement != null ) {
    				String originalValue = originalElement.toString();
    				String coercedValue = coercedElement.toString();
    				if ( !originalValue.equals(coercedValue) ) {
    					if ( sb.length() > 0 ) sb.append(";");
    					sb.append(" [");
						sb.append(originalValue);
		    			sb.append("->");
						sb.append(coercedValue);
		    			sb.append("]");
    				}
    			}
    		}
    		if ( sb.length() > 0 ) {
    			sb.insert(0, "The following elements were coerced during storage: ");
		    	HttpUserInfo userInfo = new HttpUserInfo(AuditMessage.isEnableDNSLookups());
		    	PatientRecordMessage msg = new PatientRecordMessage(PatientRecordMessage.UPDATE);
		    	msg.addUserPerson(userInfo.getUserId(), null, null, userInfo.getHostName(), true);
		    	PersonName pn = ds.getPersonName(Tags.PatientName);
		    	String pname = pn != null ? pn.format() : null;
		    	ParticipantObject patient = msg.addPatient(ds.getString(Tags.PatientID), pname);
		    	patient.addParticipantObjectDetail("Description", sb.toString());
		    	msg.validate();
		    	Logger.getLogger("auditlog").info(msg);
    		}
    	}
	}

	private String[] selectReferencedDirectoryURI(String uri) {
        if ( referencedDirectoryPath == null ) {
            log.debug("ReferencedDirectoryPath is set to ALL! uri:"+uri);
            try {
                FileSystemDTO[] fsDTOs = getFileSystemMgt().getFileSystemsOfGroup(this.refFileSystemGroupID);
                String dir, fsUri;
                for ( FileSystemDTO dto : fsDTOs ) {
                    dir = dto.getDirectoryPath();
                    fsUri = isURI(dir) ? dir+"/" : FileUtils.toFile(dir).toURI().toString();
                    log.debug("Filesystem URI:"+fsUri);
                    if (uri.startsWith(fsUri)) {
                        return new String[]{ dir, fsUri};
                    }
                }
            } catch (Exception x ) {
                log.error("Can't get FilesystemMgt Bean!",x);
            }
        } else {
            for ( int i = 0; i< referencedDirectoryURI.length ; i++) {
                if ( uri.startsWith(referencedDirectoryURI[i]) ) {
                    return new String[]{referencedDirectoryPath[i], referencedDirectoryURI[i]};
                }
            }
        }
        return null;
    }

    protected SeriesStored initSeriesStored(Dataset ds, String callingAET,
            String retrieveAET) {
        Dataset patAttrs = AttributeFilter.getPatientAttributeFilter().filter(ds);
        Dataset studyAttrs = AttributeFilter.getStudyAttributeFilter().filter(ds);
        Dataset seriesAttrs = AttributeFilter.getSeriesAttributeFilter().filter(ds);
        Dataset ian = DcmObjectFactory.getInstance().newDataset();
        ian.putUI(Tags.StudyInstanceUID, ds.getString(Tags.StudyInstanceUID));
        Dataset refSeries = ian.putSQ(Tags.RefSeriesSeq).addNewItem();
        refSeries.putUI(Tags.SeriesInstanceUID, ds.getString(Tags.SeriesInstanceUID));
        refSeries.putSQ(Tags.RefSOPSeq);
        Dataset pps = seriesAttrs.getItem(Tags.RefPPSSeq);
        DcmElement refPPSSeq = ian.putSQ(Tags.RefPPSSeq);
        if (pps != null) {
            if (!pps.contains(Tags.PerformedWorkitemCodeSeq)) {
                pps.putSQ(Tags.PerformedWorkitemCodeSeq);
            }
            refPPSSeq.addItem(pps);
        }
        return new SeriesStored(callingAET, retrieveAET, patAttrs, studyAttrs,
                seriesAttrs, ian);
    }

    private void appendInstanceToSeriesStored(SeriesStored seriesStored,
            Dataset ds, String retrieveAET, String availability) {
        Dataset refSOP = seriesStored.getIAN()
                .get(Tags.RefSeriesSeq).getItem()
                .get(Tags.RefSOPSeq).addNewItem();
        refSOP.putUI(Tags.RefSOPClassUID, ds.getString(Tags.SOPClassUID));
        refSOP.putUI(Tags.RefSOPInstanceUID, ds.getString(Tags.SOPInstanceUID));
        refSOP.putAE(Tags.RetrieveAET, retrieveAET);
        refSOP.putCS(Tags.InstanceAvailability, availability);
    }

    private void checkAppendPermission(Association a, Dataset ds)
            throws Exception {
        if (service.hasUnrestrictedAppendPermissions(a.getCallingAET())) {
            return;
        }
        // only check on first instance of a series received in the same
        // association
        String seriuid = ds.getString(Tags.SeriesInstanceUID);
        SeriesStored seriesStored = getSeriesStored(a,seriuid);
        if (seriesStored != null
                && seriuid.equals(seriesStored.getSeriesInstanceUID())) {
            return;
        }
        String suid = ds.getString(Tags.StudyInstanceUID);
        if (!getStorage(a).studyExists(suid)) {
            return;
        }

        Subject subject = (Subject) a.getProperty("user");
        if (subject == null) {
            throw new DcmServiceException(MISSING_USER_ID_ERR_STATUS,
                    MISSING_USER_ID_ERR_MSG);
        }
        if (!service.getStudyPermissionManager(a).hasPermission(suid,
                StudyPermissionDTO.APPEND_ACTION, subject)) {
            throw new DcmServiceException(NO_APPEND_PERMISSION_ERR_STATUS,
                    NO_APPEND_PERMISSION_ERR_MSG);
        }
    }

    private boolean checkOnlyWellKnownInstances(Association assoc, String iuid, String callingAET) throws Exception {
        if (contains(onlyWellKnownInstancesCallingAETs, callingAET)) {
            return getStorage(assoc).instanceExists(iuid);
        }
        return true;
    }

    private Dataset merge(Dataset ds, Dataset merge) {
        if (ds == null) {
            return merge;
        }
        if (merge == null) {
            return ds;
        }
        ds.putAll(merge, Dataset.MERGE_ITEMS);
        return ds;
    }

    private Dataset mergeMatchingMWLItem(Association assoc, Dataset ds,
            String seriuid, Dataset mwlFilter) {
        List mwlItems;
        log.info("Query for matching worklist entries for received Series["
                + seriuid + "]");
        try {
            mwlItems = service.findMWLEntries(mwlFilter);
        } catch (Exception e) {
            log.error(
                    "Query for matching worklist entries for received Series["
                            + seriuid + "] failed:", e);
            return null;
        }
        int size = mwlItems.size();
        log.info("" + size
                + " matching worklist entries found for received Series[ "
                + seriuid + "]");
        if (size == 0) {
            return null;
        }
        String callingAET = assoc.getCallingAET();
        Dataset coerce = service.getCoercionAttributesFor(callingAET,
                MWL2STORE_XSL, (Dataset) mwlItems.get(0), assoc);
        if (coerce == null) {
            log
                    .error("Failed to find or load stylesheet "
                            + MWL2STORE_XSL
                            + " for "
                            + callingAET
                            + ". Cannot coerce object attributes with request information.");
            return null;
        }
        if (size > 1) {
            DcmElement rqAttrsSq = coerce.get(Tags.RequestAttributesSeq);
            Dataset coerce0 = coerce
                    .exclude(new int[] { Tags.RequestAttributesSeq });
            for (int i = 1; i < size; i++) {
                Dataset coerce1 = service.getCoercionAttributesFor(callingAET,
                        MWL2STORE_XSL, (Dataset) mwlItems.get(i), assoc);
                if (!coerce1.match(coerce0, true, true)) {
                    log
                            .warn("Several ("
                                    + size
                                    + ") matching worklist entries "
                                    + "found for received Series[ "
                                    + seriuid
                                    + "], which differs also in attributes NOT mapped to the Request Attribute Sequence item "
                                    + "- Do not coerce object attributes with request information.");
                    return null;
                }
                if (rqAttrsSq != null) {
                    Dataset item = coerce1.getItem(Tags.RequestAttributesSeq);
                    if (item != null) {
                        rqAttrsSq.addItem(item);
                    }
                }
            }
        }
        service.coerceAttributes(ds, coerce);
        return coerce;
    }

    private boolean checkIncorrectWorklistEntry(Dataset ds) throws Exception {
        Dataset refPPS = ds.getItem(Tags.RefPPSSeq);
        if (refPPS == null) {
            return false;
        }
        String ppsUID = refPPS.getString(Tags.RefSOPInstanceUID);
        if (ppsUID == null) {
            return false;
        }
        Dataset mpps;
        try {
            mpps = getMPPSManager().getMPPS(ppsUID);
        } catch (ObjectNotFoundException e) {
            return false;
        }
        Dataset item = mpps.getItem(Tags.PPSDiscontinuationReasonCodeSeq);
        return item != null && "110514".equals(item.getString(Tags.CodeValue))
                && "DCM".equals(item.getString(Tags.CodingSchemeDesignator));
    }

    private MPPSManager getMPPSManager() throws CreateException,
            RemoteException, HomeFactoryException {
        return ((MPPSManagerHome) EJBHomeFactory.getFactory().lookup(
                MPPSManagerHome.class, MPPSManagerHome.JNDI_NAME)).create();
    }

    private FileSystemMgt2 getFileSystemMgt() throws RemoteException,
            CreateException, HomeFactoryException {
        return ((FileSystemMgt2Home) EJBHomeFactory.getFactory().lookup(
                FileSystemMgt2Home.class, FileSystemMgt2Home.JNDI_NAME)).create();
    }

    private byte[] getByteBuffer(Association assoc) {
        byte[] buf = (byte[]) assoc.getProperty(RECEIVE_BUFFER);
        if (buf == null) {
            buf = new byte[service.getBufferSize()];
            assoc.putProperty(RECEIVE_BUFFER, buf);
        }
        return buf;
    }

    private boolean containsLocal(List duplicates) {
        for (int i = 0, n = duplicates.size(); i < n; ++i) {
            FileDTO dto = (FileDTO) duplicates.get(i);
            if (service.isFileSystemGroupLocalAccessable(
                    dto.getFileSystemGroupID()))
                return true;
        }
        return false;
    }

    private boolean ignoreDuplicate(List duplicates, byte[] md5sum) {
        for (int i = 0, n = duplicates.size(); i < n; ++i) {
            FileDTO dto = (FileDTO) duplicates.get(i);
            if (storeDuplicateIfDiffMD5
                    && !(Arrays.equals(md5sum, dto.getFileMd5())
                    || Arrays.equals(md5sum, dto.getOrigMd5())))
                continue;
            if (storeDuplicateIfDiffHost
                    && !service.isFileSystemGroupLocalAccessable(
                            dto.getFileSystemGroupID()))
                continue;
            return true;
        }
        return false;
    }

    private void deleteFailedStorage(File file) {
        if (file == null) {
            return;
        }
        log.info("M-DELETE file:" + file);
        file.delete();
        // purge empty series and study directory
        File seriesDir = file.getParentFile();
        if (seriesDir.delete()) {
            seriesDir.getParentFile().delete();
        }
    }

    protected Dataset updateDB(Storage storage, Dataset ds, long fspk,
            String filePath, long fileLength, byte[] md5, byte[] origMd5,
            boolean updateStudyAccessTime)
            throws DcmServiceException, NonUniquePatientIDException {
        int retry = 0;
        for (;;) {
            try {
                if (serializeDBUpdate) {
                    synchronized (storage) {
                        return storage.store(ds, fspk, filePath, fileLength,
                                md5, origMd5, updateStudyAccessTime,
                                service.patientMatching());
                    }
                } else {
                    return storage.store(ds, fspk, filePath, fileLength,
                            md5, origMd5, updateStudyAccessTime,
                            service.patientMatching());
                }
            } catch (NonUniquePatientIDException e) {
                throw e;
            } catch (Exception e) {
                ++retry;
                if (retry > updateDatabaseMaxRetries) {
                    service.getLog().error(
                            "failed to update DB with entries for received "
                                    + filePath, e);
                    throw new DcmServiceException(Status.ProcessingFailure, e);
                }
                maxCountUpdateDatabaseRetries = Math.max(retry,
                        maxCountUpdateDatabaseRetries);
                service.getLog().warn(
                        "failed to update DB with entries for received "
                                   + filePath + " - retry", e);
                try {
                    Thread.sleep(updateDatabaseRetryInterval);
                } catch (InterruptedException e1) {
                    log.warn("update Database Retry Interval interrupted:", e1);
                }
            }
        }
    }

    protected Storage getStorage(Association assoc) throws RemoteException,
            CreateException, HomeFactoryException {
        Storage store = (Storage) assoc.getProperty(StorageHome.JNDI_NAME);
        if (store == null) {
            store = service.getStorage();
            assoc.putProperty(StorageHome.JNDI_NAME, store);
        }
        return store;
    }

    File makeFile(File basedir, Dataset ds, String callingAET) throws Exception {
        Calendar date = Calendar.getInstance();
        StringBuffer filePath = new StringBuffer();
        if( sourceAETInFilePath && callingAET != null) {
        	filePath.append(callingAET);
            filePath.append(File.separatorChar);
        }
        if (studyDateInFilePath) {
            Date studyDate = ds.getDateTime(Tags.StudyDate, Tags.StudyTime);
            if (studyDate != null)
                date.setTime(studyDate);
        }
        if (yearInFilePath) {
            filePath.append(String.valueOf(date.get(Calendar.YEAR)));
            filePath.append(File.separatorChar);
        }
        if (monthInFilePath) {
            filePath.append(String.valueOf(date.get(Calendar.MONTH) + 1));
            filePath.append(File.separatorChar);
        }
        if (dayInFilePath) {
            filePath.append(String.valueOf(date.get(Calendar.DAY_OF_MONTH)));
            filePath.append(File.separatorChar);
        }
        if (hourInFilePath) {
            filePath.append(String.valueOf(date.get(Calendar.HOUR_OF_DAY)));
            filePath.append(File.separatorChar);
        }
        filePath.append(FileUtils.toHex(ds.getString(Tags.StudyInstanceUID)
                .hashCode()));
        filePath.append(File.separatorChar);
        filePath.append(FileUtils.toHex(ds.getString(Tags.SeriesInstanceUID)
                .hashCode()));
        File dir = new File(basedir, filePath.toString());
        return FileUtils.createNewFile(dir, ds.getString(Tags.SOPInstanceUID)
                .hashCode());
    }

    private byte[] storeToFile(DcmParser parser, Dataset ds, final File file,
            CompressCmd compressCmd, byte[] buffer) throws Exception {
        log.info("M-WRITE file:" + file);
        MessageDigest md = null;
        BufferedOutputStream bos = null;
        FileOutputStream fos = new FileOutputStream(file);
        if (service.isMd5sum()) {
            md = MessageDigest.getInstance("MD5");
            DigestOutputStream dos = new DigestOutputStream(fos, md);
            bos = new BufferedOutputStream(dos, buffer);
        } else {
            bos = new BufferedOutputStream(fos, buffer);
        }
        try {
            DcmDecodeParam decParam = parser.getDcmDecodeParam();
            String tsuid = ds.getFileMetaInfo().getTransferSyntaxUID();
            DcmEncodeParam encParam = DcmEncodeParam.valueOf(tsuid);
            ds.writeFile(bos, encParam);
            if (parser.getReadTag() == Tags.PixelData) {
                int len = parser.getReadLength();
                InputStream in = parser.getInputStream();
                if (encParam.encapsulated) {
                    ds.writeHeader(bos, encParam, Tags.PixelData, VRs.OB, -1);
                    if (decParam.encapsulated) {
                        parser.parseHeader();
                        while (parser.getReadTag() == Tags.Item) {
                            len = parser.getReadLength();
                            ds.writeHeader(bos, encParam, Tags.Item, VRs.NONE,
                                    len);
                            bos.copyFrom(in, len);
                            parser.parseHeader();
                        }
                        len = parser.getReadLength();
                    } else {
                        int read = compressCmd.compress(decParam.byteOrder,
                                parser.getInputStream(), bos, null);
                        skipFully(in, parser.getReadLength() - read);
                    }
                    ds.writeHeader(bos, encParam, Tags.SeqDelimitationItem,
                            VRs.NONE, 0);
                } else {
                    ds.writeHeader(bos, encParam, Tags.PixelData, parser
                            .getReadVR(), len);
                    bos.copyFrom(in, len);
                }
                parser.parseDataset(decParam, -1);
            }

            Dataset subSet = ds.subSet(Tags.PixelData + 1, -1);
            if (!subSet.isEmpty()) {
                putPrivatePostPixelIndicator(ds);
            }

            subSet.writeDataset(bos, encParam);

            bos.flush();
            if (service.isSyncFileBeforeCStoreRSP()) {
                fos.getFD().sync();
            } else if (service.isSyncFileAfterCStoreRSP()) {
                final FileOutputStream fos2 = fos;
                syncFileExecutor().execute(new Runnable() {
                    public void run() {
                        try {
                            fos2.getFD().sync();
                        } catch (Exception e) {
                            log.error("sync of " + file + " failed:", e);
                        } finally {
                            try {
                                fos2.close();
                            } catch (Exception ignore) {}
                        }
                    }});
                fos = null;
            }
        } finally {
            if (fos != null)
                try {
                    fos.close();
                } catch (Exception ignore) {}
        }
        return md != null ? md.digest() : null;
    }

	protected void putPrivatePostPixelIndicator(Dataset ds) {
		String creatorId = ds.getPrivateCreatorID();
		ds.setPrivateCreatorID(PrivateTags.CreatorID);
		ds.putIS(PrivateTags.InstanceContainsPostPixelData, 1);
		ds.setPrivateCreatorID(creatorId);
	}

    private Executor syncFileExecutor() {
        Executor result = syncFileExecutor;
        if (result == null) {
            synchronized (this) {
                result = syncFileExecutor;
                if (result == null) {
                    syncFileExecutor = result
                        = Executors.newSingleThreadExecutor();
                }
            }
        }
        return result;
    }

    private static void skipFully(InputStream in, int n) throws IOException {
        int remaining = n;
        int skipped = 0;
        while (remaining > 0) {
            if ((skipped = (int) in.skip(remaining)) == 0) {
                throw new EOFException();
            }
            remaining -= skipped;
        }
    }

    private String checkSOPInstanceUID(Command rqCmd, Dataset ds, String aet)
            throws DcmServiceException {
        String cuid = checkNotNull(ds.getString(Tags.SOPClassUID),
                "Missing SOP Class UID (0008,0016)");
        String iuid = checkNotNull(ds.getString(Tags.SOPInstanceUID),
                "Missing SOP Instance UID (0008,0018)");
        checkNotNull(ds.getString(Tags.StudyInstanceUID),
                "Missing Study Instance UID (0020,000D)");
        checkNotNull(ds.getString(Tags.SeriesInstanceUID),
                "Missing Series Instance UID (0020,000E)");
        if (!rqCmd.getAffectedSOPInstanceUID().equals(iuid)) {
            String prompt = "SOP Instance UID in Dataset [" + iuid
                    + "] differs from Affected SOP Instance UID["
                    + rqCmd.getAffectedSOPInstanceUID() + "]";
            log.warn(prompt);
            if (!contains(acceptMismatchIUIDCallingAETs, aet)) {
                throw new DcmServiceException(
                        Status.DataSetDoesNotMatchSOPClassError, prompt);
            }
        }
        if (!rqCmd.getAffectedSOPClassUID().equals(cuid)) {
            throw new DcmServiceException(
                    Status.DataSetDoesNotMatchSOPClassError,
                    "SOP Class UID in Dataset differs from Affected SOP Class UID");
        }
        return iuid;
    }

    private static String checkNotNull(String val, String msg)
            throws DcmServiceException {
        if (val == null) {
            throw new DcmServiceException(
                    Status.DataSetDoesNotMatchSOPClassError, msg);
        }
        return val;
    }

    private void checkPatientIdAndName(Dataset ds, String aet)
            throws DcmServiceException, HomeFactoryException, RemoteException,
            CreateException, FinderException {
        String pid = ds.getString(Tags.PatientID);
        String pname = ds.getString(Tags.PatientName);
        if (pid == null && !acceptMissingPatientID) {
            throw new DcmServiceException(
                    Status.DataSetDoesNotMatchSOPClassError,
                    "Acceptance of objects without Patient ID is disabled");
        }
        if (pname == null && !acceptMissingPatientName) {
            throw new DcmServiceException(
                    Status.DataSetDoesNotMatchSOPClassError,
                    "Acceptance of objects without Patient Name is disabled");
        }
    }

    private boolean contains(Object[] a, Object e) {
        for (int i = 0; i < a.length; i++) {
            if (a[i].equals(e)) {
                return true;
            }
        }
        return false;
    }

    // Implementation of AssociationListener

    public void write(Association src, PDU pdu) {
        if (pdu instanceof AAssociateAC)
            perfMon.assocEstEnd(src, Command.C_STORE_RQ);
    }

    public void received(Association src, PDU pdu) {
        if (pdu instanceof AAssociateRQ)
            perfMon.assocEstStart(src, Command.C_STORE_RQ);
    }

    public void write(Association src, Dimse dimse) {
    }

    public void received(Association src, Dimse dimse) {
    }

    public void error(Association src, IOException ioe) {
    }

    public void closing(Association assoc) {
        if (assoc.getAAssociateAC() != null)
            perfMon.assocRelStart(assoc, Command.C_STORE_RQ);

		notifySeriesStoredOnClose(assoc);

    }

    public void closed(Association assoc) {
        if (assoc.getAAssociateAC() != null)
            perfMon.assocRelEnd(assoc, Command.C_STORE_RQ);
    }

    // extension point for specialized implementations of StoreScp
    protected void doAfterSeriesIsStored(Storage store, Association assoc, SeriesStored seriesStored) throws Exception {
    	return;
    }

    /****** Refactored code for different Series Stored notification handling ******/

	protected SeriesStored setSeriesStored(Dataset ds, Association assoc,
			String callingAET, FileSystemDTO fsDTO, SeriesStored seriesStored,
			boolean newSeries, String seriesUid) {
		if (newSeries) {
			seriesStored = initSeriesStored(ds, callingAET, fsDTO.getRetrieveAET());
		    assoc.putProperty(SERIES_STORED, seriesStored);
		}
		return seriesStored;
	}

	protected SeriesStored getSeriesStored(Association assoc, String seriuid) throws RemoteException, FinderException {
		SeriesStored seriesStored = (SeriesStored) assoc.getProperty(SERIES_STORED);
		return seriesStored;
	}

	protected void notifyOnSeriesStored(SeriesStored seriesStored, Association assoc, Storage store,
			String seriuid) throws Exception {

		if (seriesStored != null
		        && !seriuid.equals(seriesStored.getSeriesInstanceUID())) {
		    log.debug("Send SeriesStoredNotification - series changed");
			service.logInstancesStoredAndUpdateDerivedFields(
				store, assoc.getSocket(), seriesStored);
		    doAfterSeriesIsStored(store, assoc, seriesStored);
		    seriesStored = null;
		}
	}

	protected void notifySeriesStoredOnClose(Association assoc) {
        SeriesStored seriesStored = (SeriesStored) assoc.getProperty(SERIES_STORED);
        if (seriesStored != null) {
            try {
            	Storage store = getStorage(assoc);
                service.logInstancesStoredAndUpdateDerivedFields(
                		store, assoc.getSocket(), seriesStored);
                doAfterSeriesIsStored(store, assoc, seriesStored);
             } catch (Exception e) {
                log.error("Clean up on Association close failed:", e);
            }
        }
	}
}

redpajama_set_name: RedPajamaGithub


The new Defence Sector Code was gazetted on 9 November 2018 by the Department of Trade and Industry. This Sector Code also came into effect on the date of publication.
It will be applicable to all enterprises in the South African Defence Industry (SADI) – these include National or Provincial Departments, Organs of State, Public Entities as well as private enterprises providing defence material and/or any other supplies, products and services to the Department of Defence or its agencies. SADI is also the collective term for South African Defence Related Industries and means those entities in public or private sector, including commercial and business units such as entities who are directly or indirectly active in the design, research, development, manufacturing and marketing of Defence Materiel.
Black Military Veterans will be taken into consideration with the Ownership, Management & Control as well as the Skills element.
This new Sector Code also makes provision for a new indicator namely Enterprise & Supplier Development Fund as well as a new element, Localisation. The Localisation element deals with procurement of defence material from local suppliers. The Enterprise & Supplier Development Fund is a fund that will be set up and approved by the Department of Defence and the Department of Trade and Industry. This fund will be administrated by the Defence Charter Council and will be utilised for Enterprise and Supplier Development initiatives.