Skip to content

Commit dd6fe6a

Browse files
committed
Some codes for hello lithosphere tutorials.
1 parent 73458af commit dd6fe6a

File tree

12 files changed

+113
-40
lines changed

12 files changed

+113
-40
lines changed

client/edge/pom.xml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
<packaging>jar</packaging>
1919

2020
<dependencies>
21+
<dependency>
22+
<groupId>com.thefirstlineofcode.chalk</groupId>
23+
<artifactId>chalk-logger</artifactId>
24+
</dependency>
2125
<dependency>
2226
<groupId>com.thefirstlineofcode.sand.client</groupId>
2327
<artifactId>sand-client-ibtr</artifactId>

client/edge/src/main/java/com/thefirstlineofcode/sand/client/edge/AbstractEdgeThing.java

Lines changed: 91 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import com.thefirstlineofcode.chalk.core.StandardChatClient;
3535
import com.thefirstlineofcode.chalk.core.stream.StandardStreamConfig;
3636
import com.thefirstlineofcode.chalk.core.stream.UsernamePasswordToken;
37+
import com.thefirstlineofcode.chalk.logger.LogConfigurator;
3738
import com.thefirstlineofcode.chalk.network.ConnectionException;
3839
import com.thefirstlineofcode.chalk.network.IConnectionListener;
3940
import com.thefirstlineofcode.sand.client.ibtr.IRegistration;
@@ -49,7 +50,7 @@ public abstract class AbstractEdgeThing extends AbstractThing implements IEdgeTh
4950
private static final String INTERNET_CONNECTIVITY_TEST_ADDRESS = "http://www.baidu.com";
5051
private static final String SAND_EDGE_CONFIG_DIR = ".com.thefirstlineofcode.sand.client.edge";
5152

52-
private static final Logger logger = LoggerFactory.getLogger(AbstractEdgeThing.class);
53+
private static final Logger logger = LogConfigurator.isConfigured() ? LoggerFactory.getLogger(AbstractEdgeThing.class) : null;
5354

5455
protected StandardStreamConfig streamConfig;
5556
protected RegisteredThing registeredThing;
@@ -108,7 +109,9 @@ protected StandardStreamConfig getStreamConfig(Map<String, String> attributes) {
108109

109110
StringTokenizer st = new StringTokenizer(sStreamConfig, ",");
110111
if (st.countTokens() != 3) {
111-
logger.error("Can't read stream config. Not a valid stream config string.");
112+
if (LogConfigurator.isConfigured())
113+
logger.error("Can't read stream config. Not a valid stream config string.");
114+
112115
throw new IllegalArgumentException("Can't read stream config. Not a valid stream config string.");
113116
}
114117

@@ -145,7 +148,8 @@ public void start() {
145148
try {
146149
doStart();
147150
} catch (Exception e) {
148-
logger.error("Some thing is wrong. The program can't run correctly.", e);
151+
if (LogConfigurator.isConfigured())
152+
logger.error("Some thing is wrong. The program can't run correctly.", e);
149153

150154
throw new RuntimeException("Some thing is wrong. The program can't run correctly.", e);
151155
}
@@ -178,8 +182,13 @@ protected void doStart() {
178182
if (streamConfig == null)
179183
throw new IllegalStateException("Null stream config.");
180184

181-
logger.info("I'm an edge thing[thing_id='{}', host='{}', port='{}', tls_preferred='{}'].",
182-
thingId, this.streamConfig.getHost(), this.streamConfig.getPort(), this.streamConfig.isTlsPreferred());
185+
if (LogConfigurator.isConfigured()) {
186+
logger.info("I'm an edge thing[thing_id='{}', host='{}', port='{}', tls_preferred='{}'].",
187+
thingId, this.streamConfig.getHost(), this.streamConfig.getPort(), this.streamConfig.isTlsPreferred());
188+
} else {
189+
System.out.println(String.format("I'm an edge thing[thing_id='%s', host='%s', port='%s', tls_preferred='%s'].",
190+
thingId, this.streamConfig.getHost(), this.streamConfig.getPort(), this.streamConfig.isTlsPreferred()));
191+
}
183192

184193
if (!isHostLocalLanAddress()) {
185194
checkInternetConnectivity(10);
@@ -203,7 +212,11 @@ protected void doStart() {
203212
connect();
204213
}
205214

206-
logger.info("The thing has started.");
215+
if (LogConfigurator.isConfigured())
216+
logger.info("The thing has started.");
217+
else
218+
System.out.println("The thing has started.");
219+
207220
started = true;
208221

209222
if (startConsole) {
@@ -217,7 +230,10 @@ private void checkInternetConnectivity(int retryTimes) {
217230
while (!checkInternetConnectivity()) {
218231
i++;
219232

220-
logger.info("No internet connection. Waiting for a while then trying again....");
233+
if (LogConfigurator.isConfigured())
234+
logger.info("No internet connection. Waiting for a while then trying again....");
235+
else
236+
System.out.println("No internet connection. Waiting for a while then trying again....");
221237

222238
try {
223239
Thread.sleep(2000);
@@ -227,7 +243,11 @@ private void checkInternetConnectivity(int retryTimes) {
227243
}
228244

229245
if (i == retryTimes) {
230-
logger.error("No internet connection. The thing can't be started.");
246+
if (LogConfigurator.isConfigured())
247+
logger.error("No internet connection. The thing can't be started.");
248+
else
249+
System.out.println("No internet connection. The thing can't be started.");
250+
231251
throw new IllegalStateException("No internet connection. The program will exit.");
232252
}
233253
}
@@ -315,7 +335,10 @@ public void connect() {
315335
chatClient.addConnectionListener(this);
316336
}
317337

318-
logger.info("The thing tries to connect to server.");
338+
if (LogConfigurator.isConfigured())
339+
logger.info("The thing tries to connect to server.");
340+
else
341+
System.out.println("The thing tries to connect to server.");
319342

320343
try {
321344
chatClient.connect(new UsernamePasswordToken(registeredThing.getThingName(),
@@ -385,7 +408,10 @@ protected void registered(RegisteredThing registeredThing) {
385408

386409
this.registeredThing = registeredThing;
387410

388-
logger.info("The thing has registered. Thing name is '{}'.", registeredThing.getThingName());
411+
if (LogConfigurator.isConfigured())
412+
logger.info("The thing has registered. Thing name is '{}'.", registeredThing.getThingName());
413+
else
414+
System.out.println(String.format("The thing has registered. Thing name is '%s'.", registeredThing.getThingName()));
389415
}
390416

391417
@Override
@@ -402,9 +428,12 @@ public void stop() {
402428
disconnect();
403429
}
404430

405-
logger.info("The thing has stopped.");
406-
started = false;
431+
if (LogConfigurator.isConfigured())
432+
logger.info("The thing has stopped.");
433+
else
434+
System.out.println("The thing has stopped.");
407435

436+
started = false;
408437
stopConsoleThread();
409438
}
410439

@@ -450,7 +479,10 @@ public void register() {
450479
IChatClient chatClient = new StandardChatClient(streamConfig);
451480
chatClient.register(IbtrPlugin.class);
452481

453-
logger.info("The thing tries to register to server.");
482+
if (LogConfigurator.isConfigured())
483+
logger.info("The thing tries to register to server.");
484+
else
485+
System.out.println("The thing tries to register to server.");
454486

455487
IRegistration registration = null;
456488
try {
@@ -550,8 +582,10 @@ public void run() {
550582

551583
synchronized (AbstractEdgeThing.this) {
552584
if (!isConnected()) {
553-
if (logger.isInfoEnabled())
585+
if (LogConfigurator.isConfigured())
554586
logger.info("The thing has disconnected. Try to reconnect to server....");
587+
else
588+
System.out.println("The thing has disconnected. Try to reconnect to server....");
555589

556590
connect();
557591
}
@@ -572,8 +606,10 @@ public void run() {
572606
}
573607

574608
protected void connected(IChatClient chatClient) {
575-
if (logger.isInfoEnabled())
609+
if (LogConfigurator.isConfigured())
576610
logger.info("The thing has connected to server.");
611+
else
612+
System.out.println("The thing has connected to server.");
577613

578614
startIotComponents();
579615
startAutoReconnectThread();
@@ -583,24 +619,37 @@ protected void connected(IChatClient chatClient) {
583619
}
584620

585621
protected void FailedToConnect(ConnectionException e) {
586-
logger.error("The thing failed to connect to server.", e);
622+
if (LogConfigurator.isConfigured()) {
623+
logger.error("The thing failed to connect to server.", e);
624+
} else {
625+
System.out.println("The thing failed to connect to server.");
626+
e.printStackTrace();
627+
}
587628
}
588629

589630
protected void failedToAuth(AuthFailureException e) {
590-
logger.error("The thing failed to auth to server.", e);
631+
if (LogConfigurator.isConfigured())
632+
logger.error("The thing failed to auth to server.", e);
591633

592634
throw new RuntimeException("Failed to auth to server.", e);
593635
}
594636

595637
protected void disconnected() {
596638
stopIotComponents();
597639

598-
if (logger.isInfoEnabled())
640+
if (LogConfigurator.isConfigured())
599641
logger.info("The thing has disconnected from server.");
642+
else
643+
System.out.println("The thing has disconnected from server.");
600644
}
601645

602646
protected void registrationExceptionOccurred(RegistrationException e) {
603-
logger.error("Registration exception occurred.", e);
647+
if (LogConfigurator.isConfigured()) {
648+
logger.error("Registration exception occurred.", e);
649+
} else {
650+
System.out.println("Registration exception occurred.");
651+
e.printStackTrace();
652+
}
604653
}
605654

606655
protected RegisteredThing getRegisteredThing(Map<String, String> attributes) {
@@ -678,7 +727,10 @@ protected Map<String, String> loadThingAttributes() {
678727
Path attributesFilePath = getAttributesFilePath();
679728

680729
if (!Files.exists(attributesFilePath, LinkOption.NOFOLLOW_LINKS)) {
681-
logger.info("Attributes file not existed. Ignore to load attributes.");
730+
if (LogConfigurator.isConfigured())
731+
logger.info("Attributes file not existed. Ignore to load attributes.");
732+
else
733+
System.out.println("Attributes file not existed. Ignore to load attributes.");
682734

683735
return null;
684736
}
@@ -689,8 +741,9 @@ protected Map<String, String> loadThingAttributes() {
689741
reader = Files.newBufferedReader(attributesFilePath, Charset.forName(Constants.DEFAULT_CHARSET));
690742
properties.load(reader);
691743
} catch (Exception e) {
692-
logger.error(String.format("Can't load attributes from file '%s'.",
693-
attributesFilePath.toAbsolutePath()), e);
744+
if (LogConfigurator.isConfigured())
745+
logger.error("Can't load attributes from file '{}'.", attributesFilePath.toAbsolutePath(), e);
746+
694747
throw new RuntimeException(String.format("Can't load attributes from file '%s'.",
695748
attributesFilePath.toAbsolutePath()), e);
696749
} finally {
@@ -724,7 +777,9 @@ protected void saveAttributes(Map<String, String> attributes) {
724777
try {
725778
Files.move(attributesFilePath, attributesBakFilePath);
726779
} catch (IOException e) {
727-
logger.error("Can't backup attributes file.", e);
780+
if (LogConfigurator.isConfigured())
781+
logger.error("Can't backup attributes file.", e);
782+
728783
throw new RuntimeException("Can't backup attributes file.", e);
729784
}
730785
}
@@ -733,7 +788,9 @@ protected void saveAttributes(Map<String, String> attributes) {
733788
try {
734789
Files.createDirectories(attributesFilePath.getParent());
735790
} catch (IOException e) {
736-
logger.error(String.format("Can't create directory %s.", attributesFilePath.getParent().toAbsolutePath()), e);
791+
if (LogConfigurator.isConfigured())
792+
logger.error("Can't create directory {}.", attributesFilePath.getParent().toAbsolutePath(), e);
793+
737794
throw new RuntimeException(String.format("Can't create directory %s.", attributesFilePath.getParent().toAbsolutePath()), e);
738795
}
739796
}
@@ -744,10 +801,14 @@ protected void saveAttributes(Map<String, String> attributes) {
744801
StandardOpenOption.CREATE, StandardOpenOption.WRITE);
745802
properties.store(writer, null);
746803

747-
logger.info(String.format("Attributes are saved to %s.", attributesFilePath.toAbsolutePath()));
804+
if (LogConfigurator.isConfigured())
805+
logger.info("Attributes are saved to {}.", attributesFilePath.toAbsolutePath());
806+
else
807+
System.out.println(String.format("Attributes are saved to %s.", attributesFilePath.toAbsolutePath()));
748808
} catch (Exception e) {
749-
logger.error(String.format("Can't save attributes to file '%s'.",
750-
attributesFilePath.toAbsolutePath()), e);
809+
if (LogConfigurator.isConfigured())
810+
logger.error("Can't save attributes to file '{}'.", attributesFilePath.toAbsolutePath(), e);
811+
751812
throw new RuntimeException(String.format("Can't save attributes to file '%s'.",
752813
attributesFilePath.toAbsolutePath()), e);
753814
} finally {
@@ -764,7 +825,9 @@ protected void saveAttributes(Map<String, String> attributes) {
764825
try {
765826
Files.delete(attributesBakFilePath);
766827
} catch (IOException e) {
767-
logger.error("Can't delete attributes backup file.", e);
828+
if (LogConfigurator.isConfigured())
829+
logger.error("Can't delete attributes backup file.", e);
830+
768831
throw new RuntimeException("Can't delete attributes backup file.", e);
769832
}
770833
}

demo/server/src/main/java/com/thefirstlineofcode/sand/demo/server/ThingRegistrationListener.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121

2222
public class ThingRegistrationListener implements IEventListener<ThingRegistrationEvent>,
2323
IServerConfigurationAware, IDataObjectFactoryAware {
24+
private static final String USER_NAME_SAND_DEMO = "sand-demo";
25+
2426
private static final Logger logger = LoggerFactory.getLogger(ThingRegistrationListener.class);
2527

2628
@BeanDependency
@@ -33,8 +35,12 @@ public class ThingRegistrationListener implements IEventListener<ThingRegistrati
3335
private String domainName;
3436

3537
@Override
36-
public void process(IEventContext context, ThingRegistrationEvent event) {
37-
createAce(event.getThingId(), event.getAuthorizer());
38+
public void process(IEventContext context, ThingRegistrationEvent event) {
39+
String authorizer = event.getAuthorizer();
40+
if (authorizer == null)
41+
authorizer = USER_NAME_SAND_DEMO;
42+
43+
createAce(event.getThingId(), authorizer);
3844

3945
IResource[] resources = resourceService.getResources(JabberId.parse(String.format("%s@%s", event.getAuthorizer(), domainName)));
4046
if (resources == null || resources.length == 0 && logger.isWarnEnabled()) {

demo/things/lgsc-01/src/main/java/com/thefirstlineofcode/sand/demo/things/lgsc01/Main.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ private void run(String[] args) {
8181
if (logLevel == null)
8282
logLevel = "info";
8383

84-
new LogConfigurator().configure(LoraGatewayAndCamera.THING_MODEL, getLogLevel(logLevel));
84+
LogConfigurator.configure(LoraGatewayAndCamera.THING_MODEL, getLogLevel(logLevel));
8585

8686
WebcamConfig webcamConfig = new WebcamConfig(dontRunWebrtcNativeService, webrtcNativeServicePath, requestedWebcamCapability);
8787
ICommunicator<LoraAddress, LoraAddress, byte[]> communicator = null;

emulators/lora/lora-gateway/src/main/java/com/thefirstlineofcode/sand/emulators/lora/gateway/Main.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ public static void main(String[] args) {
1212
}
1313

1414
private void run() {
15-
new LogConfigurator().configure(APP_NAME_SAND_LORA_GATEWAY, LogLevel.DEBUG);
15+
LogConfigurator.configure(APP_NAME_SAND_LORA_GATEWAY, LogLevel.DEBUG);
1616

1717
Gateway gateway = new Gateway(new LoraNetwork());
1818
gateway.setVisible(true);

emulators/wifi/simple-light/src/main/java/com/thefirstlineofcode/sand/emulators/wifi/simple/light/Main.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public static void main(String[] args) {
1111
}
1212

1313
private void run() {
14-
new LogConfigurator().configure(APP_NAME_SAND_WIFI_LIGHT, LogLevel.DEBUG);
14+
LogConfigurator.configure(APP_NAME_SAND_WIFI_LIGHT, LogLevel.DEBUG);
1515
new SimpleLightFrame().setVisible(true);
1616
}
1717
}

server/lite/things/src/main/java/com/thefirstlineofcode/sand/server/lite/things/ThingManager.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ public ThingRegistered register(String thingId, String registrationCode) {
132132
thingId, registrationCode)));
133133

134134
String authorizer = null;
135-
if (registrationCustomizer == null || registrationCustomizer.isAuthenticationRequired()) {
135+
if (registrationCustomizer == null || registrationCustomizer.isAuthorizationRequired()) {
136136
ThingAuthorization authorization = getAuthorization(thingId);
137137
if (authorization == null || authorization.isCanceled() || isExpired(authorization)) {
138138
throw new ProtocolException(new NotAuthorized());
@@ -468,7 +468,7 @@ public IThingModelDescriptor[] getModelDescriptors() {
468468
@Override
469469
public boolean isAuthenticationRequired() {
470470
if (registrationCustomizer != null)
471-
return registrationCustomizer.isAuthenticationRequired();
471+
return registrationCustomizer.isAuthorizationRequired();
472472

473473
return true;
474474
}

server/lite/things/src/main/resources/META-INF/data/RegisteredThingMapper.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
44
<mapper namespace="com.thefirstlineofcode.sand.server.lite.things.RegisteredThingMapper">
55
<insert id="insert" parameterType="com.thefirstlineofcode.sand.server.lite.things.D_RegisteredThing">
6-
INSERT INTO REGISTERED_THINGS(id, thing_id, thing_name, credentials, security_key) VALUES(#{id}, #{thingId}, #{thingName}, #{credentials}, #{securityKey})
6+
INSERT INTO REGISTERED_THINGS(id, thing_id, thing_name, credentials, secret_key) VALUES(#{id}, #{thingId}, #{thingName}, #{credentials}, #{secretKey})
77
</insert>
88

99
<select id="selectByThingName" resultType="com.thefirstlineofcode.sand.server.lite.things.D_RegisteredThing">

server/lite/things/src/main/resources/META-INF/data/ThingMapper.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
44
<mapper namespace="com.thefirstlineofcode.sand.server.lite.things.ThingMapper">
55
<insert id="insert" parameterType="com.thefirstlineofcode.sand.server.lite.things.D_Thing">
6-
INSERT INTO THINGS(id, thing_id, registration_code, model, registration_time) VALUES(#{id}, #{thingId}, #{registration_code}, #{model}, #{registrationTime})
6+
INSERT INTO THINGS(id, thing_id, registration_code, model, registration_time) VALUES(#{id}, #{thingId}, #{registrationCode}, #{model}, #{registrationTime})
77
</insert>
88

99
<update id="delete">

server/lite/things/src/main/resources/META-INF/data/thing.sql

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
CREATE TABLE THING_AUTHORIZATIONS(id VARCHAR(64) PRIMARY KEY, thing_id VARCHAR(32) NOT NULL, authorizer VARCHAR(32), authorized_time TIMESTAMP NOT NULL, expired_time TIMESTAMP NOT NULL, canceled BOOLEAN DEFAULT FALSE NOT NULL);
22
CREATE TABLE THINGS(id VARCHAR(64) PRIMARY KEY, thing_id VARCHAR(32) NOT NULL, registration_code VARCHAR(32), model VARCHAR(16), software_version VARCHAR(16), registration_time TIMESTAMP NOT NULL);
3-
CREATE TABLE REGISTERED_THINGS(id VARCHAR(64) PRIMARY KEY, thing_id VARCHAR(32) NOT NULL, thing_name VARCHAR(32) NOT NULL, credentials VARCHAR(16) NOT NULL, security_key VARBINARY(24) NOT NULL)
3+
CREATE TABLE REGISTERED_THINGS(id VARCHAR(64) PRIMARY KEY, thing_id VARCHAR(32) NOT NULL, thing_name VARCHAR(32) NOT NULL, credentials VARCHAR(16) NOT NULL, secret_key VARBINARY(24) NOT NULL)
44
CREATE TABLE THING_EVEN_SUBSCRIPTIONS(id VARCHAR(64) PRIMARY KEY, target VARCHAR(32) NOT NULL, event VARCHAR(128) NOT NULL, subscriber VARCHAR(32) NOT NULL)
55
CREATE INDEX INDEX_THING_AUTHORIZATIONS_THING_ID ON THING_AUTHORIZATIONS (thing_id);
66
CREATE INDEX INDEX_THING_AUTHORIZATIONS_AUTHORIZED_TIME ON THING_AUTHORIZATIONS (authorized_time);

0 commit comments

Comments
 (0)